通常我们在操作数据库对象的时候,一般需要执行多次脚本,避免出错,所以需要添加判断对象是否存在,以及后续处理方式。下面对表,视图,存储过程,字段等对象做了判断,这样我们在操作对象的时候,把语句添加在脚本之上,就可以放心大胆的操作。
1 /* 2 1、创建表 3 */ 4 IF NOT EXISTS(SELECT 1 FROM SYSOBJECTS WHERE ID=OBJECT_ID('TABLE_NAME') AND XTYPE='U') 5 BEGIN 6 7 8 END 9 10 GO 11 12 /* 13 2、增加字段 14 */ 15 IF NOT EXISTS(SELECT 1 FROM SYSCOLUMNS WHERE ID=OBJECT_ID('TABLE_NAME') AND name='COLUMN_NAME') 16 BEGIN 17 18 END 19 20 GO 21 22 /* 23 3、创建视图 24 */ 25 IF NOT EXISTS(SELECT 1 FROM SYSOBJECTS WHERE ID=OBJECT_ID('V_VIEWNAME') AND XTYPE='v') 26 BEGIN 27 EXEC('CREATE VIEW V_VIEWNAME AS SELECT 1 AS A') 28 END 29 GO 30 ALTER VIEW DBO.V_VIEWNAME 31 AS 32 SELECT 1 AS B 33 GO 34 35 36 /* 37 4、创建函数 38 */ 39 IF EXISTS(SELECT 1 FROM SYSOBJECTS WHERE ID=OBJECT_ID('FN_FUNTIONNAME') AND XTYPE='FN') 40 BEGIN 41 DROP FUNCTION DBO.FN_FUNCTIONNAME 42 END 43 GO 44 CREATE FUNCTION DBO.FN_FUNCTIONNAME() 45 RETURNS VARCHAR(50) 46 AS 47 BEGIN 48 RETURN 'A' 49 END 50 GO 51 52 /* 53 5、创建存储过程 54 */ 55 IF EXISTS(SELECT 1 FROM SYSOBJECTS WHERE ID=OBJECT_ID('USP_PROCNAME') AND XTYPE='P') 56 BEGIN 57 DROP PROC DBO.USP_PROCNAME 58 END 59 GO 60 CREATE PROC DBO.USP_PROCNAME 61 AS 62 BEGIN 63 SELECT 1 64 END 65 66 GO