表相關(guān)
普通表
查詢(xún)普通表是否存在可以使用object_id函數(shù),下面的例子是查詢(xún)表“t_test”是否存在之后從而進(jìn)行其他的DLL操作:
if object_id('t_test') is not null begin -- 如果表存在 這段里面寫(xiě)相關(guān)邏輯 select 1 end
?文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-425771.html
臨時(shí)表
臨時(shí)表同樣可以用object_id但是表名要記得加上庫(kù)名和表空間:
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
以上這個(gè)條件自行發(fā)揮,我這邊使用的是like語(yǔ)句,判斷的是只要是#temp開(kāi)頭的臨時(shí)表存在。
字段
有一個(gè)很精簡(jiǎn)的寫(xiě)法,用COL_LENGTH函數(shù),用法:COL_LENGTH('表名','字段名')
if COL_LENGTH('d_test', 'col1') IS NULL begin -- 字段在 d_test 存在 select 1 end
索引
索引這邊比較麻煩,但是也有辦法。
可以使用存過(guò)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表索引、觸發(fā)器結(jié)構(gòu)羅列出來(lái)放在定義的變量表@index中了。這時(shí)候我們查詢(xún)這個(gè)表會(huì)得到結(jié)果:
這樣查詢(xún)索引存不存在就好辦了
if not exists(select 1 from @index where index_name = 'idx_test') begin -- 索引存在 select 1 end
?文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-425771.html
?
?
?
到了這里,關(guān)于[SQL Server 2008R2] 有關(guān)于判斷表、字段、存過(guò)等元素是否存在相關(guān)SQL寫(xiě)法的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!