puqiong233

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

[SQL Server 2008R2] 有关于判断表、字段、存过等元素是否存在相关SQL写法

表相关

普通表

  查询普通表是否存在可以使用object_id函数,下面的例子是查询表“t_test”是否存在之后从而进行其他的DLL操作:

if object_id('t_test') is not null
begin
    -- 如果表存在 这段里面写相关逻辑
    select 1 
end

 

临时表

  临时表同样可以用object_id但是表名要记得加上库名和表空间:

if object_id('tempdb..#temp') is not null
begin
    select 1
end

  或者

if exists(select 1 from tempdb..sysobjects where name like '#temp%')
begin
    -- 存在 #tempXXXX 表
    select 1
end

以上这个条件自行发挥,我这边使用的是like语句,判断的是只要是#temp开头的临时表存在。

字段

  有一个很精简的写法,用COL_LENGTH函数,用法:COL_LENGTH('表名','字段名')

if COL_LENGTH('d_test', 'col1') IS NULL
begin
    -- 字段在 d_test 存在
    select 1
end

索引

  索引这边比较麻烦,但是也有办法。

  可以使用存过sp_helpindex

declare @index table (
    index_name varchar(500),
    index_des varchar(5000),
    index_keys varchar(500)
)
insert into @index
exec sp_helpindex 't_test'

上面这段代码是将t_test表索引、触发器结构罗列出来放在定义的变量表@index中了。这时候我们查询这个表会得到结果:

这样查询索引存不存在就好办了

if not exists(select 1 from @index where index_name = 'idx_test')
begin
    -- 索引存在
    select 1
end

 

 

 


 

posted on   纯纯的牛马  阅读(198)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示