摘要:
下文讲述sqlserver中,更新脚本中经常使用if exists关键字的用法说明,以下所示:
实验环境:sql server 2008 R2 sql
1、检测数据库是否存在于当前数据库引擎下
数据库
if exists (select * from sys.databases where name = ’数据库名称’) begin print '数据库名称--存在' end
2、检测数据表是否存在于指定数据库下函数
if exists (select * from sysobjects where id = object_id(N’[数据表名称]’) and OBJECTPROPERTY(id, N’IsUserTable’) = 1) begin print '数据表名称---存在' end
3、检测存储过程是否存在的方法sqlserver
if exists (select * from sysobjects where id = object_id(N’[存储过程名称]’) and OBJECTPROPERTY(id, N’IsProcedure’) = 1) begin print '存储过程名称-存在' end
4、临时表是否存在的方法spa
if object_id(’tempdb..#临时表名’) is not null begin print '临时表名--存在' end
5、视图是否存在的方法日志
IF EXISTS (SELECT * FROM sys.views WHERE object_id = ’[dbo].[视图名称]’ begin print '视图名称存在' end
6、函数是否存在的检测方法code
if exists (select * from dbo.sysobjects where id = object_id(N’[dbo].[函数名称]’) and xtype in (N’FN’, N’IF’, N’TF’)) begin print '函数名称--存在' end
7、获取用户自定义对象信息server
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 = 扩展存储过程 */
8、检测数据列是否存在的方法对象
if exists(select * from syscolumns where id=object_id(’数据表名称’) and name=’数据列’) begin print '数据列---存在' end
9、是否为自增列检测blog
if columnproperty(object_id(’table’),’列名’,’IsIdentity’)=1 begin print 'table下“列名”为自增列' end
10、检测数据表中是否存在索引
if columnproperty(object_id(’table’),’列名’,’IsIdentity’)=1 begin print 'table下“列名”为自增列' end