mssql sqlserver if exists 用法大汇总

摘要:
下文讲述sqlserver中,更新脚本中常用if exists关键字的用法说明,如下所示:
实验环境:sql server 2008 r2

 
一、检测数据库是否存在于当前数据库引擎下
 

if exists (select * from sys.databases where name = ’数据库名称’)
begin
print '数据库名称--存在' 
end 

二、检测数据表是否存在于指定数据库下

 if exists (select * from sysobjects where id = object_id(n’[数据表名称]’) and objectproperty(id, n’isusertable’) = 1) 
begin
print '数据表名称---存在'
end

三、检测存储过程是否存在的方法

 

if exists (select * from sysobjects where id = object_id(n’[存储过程名称]’) and objectproperty(id, n’isprocedure’) = 1) 
begin
print '存储过程名称-存在' 
end

四、临时表是否存在的方法

if object_id(’tempdb..#临时表名’) is not null 
begin
print '临时表名--存在'
end

五、视图是否存在的方法

 if exists (select * from sys.views where object_id = ’[dbo].[视图名称]’ 
begin
print '视图名称存在'
end 

六、函数是否存在的检测方法

if exists (select * from dbo.sysobjects where id = object_id(n’[dbo].[函数名称]’) and xtype in (n’fn’, n’if’, n’tf’)) 
begin
print '函数名称--存在'
end

七、获取用户自定义对象信息

 

select [name] as [对象名称],
[id] as [对象编号],
crdate as [对象创建时间] 
from sysobjects 
where xtype=’u’ 
/*
xtype 参数类型,可输以下值 
c = check 约束 
d = 默认值或 default 约束 
f = foreign key 约束 
l = 日志 
fn = 标量函数 
if = 内嵌表函数 
p = 存储过程 
pk = primary key 约束(类型是 k) 
rf = 复制筛选存储过程 
s = 系统表 
tf = 表函数 
tr = 触发器 
u = 用户表 
uq = unique 约束(类型是 k) 
v = 视图 
x = 扩展存储过程 
*/

 

八、检测数据列是否存在的方法

if exists(select * from syscolumns where id=object_id(’数据表名称’) and name=’数据列’) 
begin
print '数据列---存在'
end 

 九、是否为自增列检测

 

if columnproperty(object_id(’table’),’列名’,’isidentity’)=1 
begin
print 'table下“列名”为自增列'
end

 

 十、检测数据表中是否存在索引

 

if columnproperty(object_id(’table’),’列名’,’isidentity’)=1 
begin
print 'table下“列名”为自增列'
end

 

 

(0)
上一篇 2022年3月21日
下一篇 2022年3月21日

相关推荐