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

 

 

 转自:http://www.maomao365.com/?p=9094

posted @ 2019-07-09 22:14  Adeal2008  阅读(4779)  评论(0编辑  收藏  举报