1、判断表是否存在
IF EXISTS(select * from dbo.sysobjects where id = object_id(N'[dbo].[Animals]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) --do something
或者
if OBJECT_ID(N'UserInfos',N'U') is not null --do something
1.1、判断某个表字段是否存在
IF NOT EXISTS(SELECT a.Name FROM syscolumns a INNER JOIN sysobjects b ON a.ID=b.ID WHERE b.Name='Animals' AND a.Name='DeathTime') BEGIN ALTER TABLE dbo.Animals ADD DeathTime DATETIME NULL --不存在就添加 END
1.2、判断临时表是否存在
if exists (select * from tempdb.dbo.sysobjects where id = object_id(N'tempdb..#TempUsers') and type='U') print '临时表#TempUsers 存在!'
或者
if OBJECT_ID(N'tempdb..#TempUsers',N'U') is not null print '临时表#TempUsers 存在!'
2、判断视图是否存在
IF EXISTS (SELECT * FROM sysobjects WHERE name = N'VWinbidInfoBrowse') DROP VIEW VWinbidInfoBrowse
3、判断存储过程是否存在
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Gp_GetAnimalNo]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) DROP PROCEDURE [dbo].[Gp_GetAnimalNo] --存在则删除 GO