1、判斷數據庫是否存在
if exists (select * from sys.databases where name = '數據庫名')
drop database [數據庫名]
2 判斷表是否存在
IF NOT EXISTS ( SELECT *
FROM sysobjects
WHERE id = OBJECT_ID('cb_DBDossierTypeSet')
AND type = 'U' )
。。。。。。
GO
3 判斷存儲過程是否存在
IF ( SELECT OBJECT_ID('GetUserNameList')
) IS NOT NULL
DROP PROC GetUserNameList
go
4 判斷臨時表是否存在
if object_id('tempdb..#臨時表名') is not null
drop table #臨時表名
5 判斷視圖是否存在
IF EXISTS ( SELECT *
FROM sysobjects
WHERE id = OBJECT_ID('vcb_DBZhJsIndex')
AND type = 'V' )
DROP VIEW vcb_DBZhJsIndex
GO
6 判斷函數是否存在
-- 判斷要創建的函數名是否存在
IF ( SELECT OBJECT_ID('[fn_bbb]')
) IS NOT NULL
DROP FUNCTION [fn_bbb]
go
7 獲取用戶創建的對象信息
SELECT [name],[id],crdate FROM sysobjects where xtype='U'
8 判斷列是否存在
IF not EXISTS ( SELECT *
FROM syscolumns
WHERE id = OBJECT_ID('cb_Product')
AND name = 'ProductLevel' )
ALTER TABLE [cb_Product] ADD [ProductLevel] [varchar] (50) ;
GO
9 判斷列是否自增列
if columnproperty(object_id('table'),'col','IsIdentity')=1
print '自增列'
else
print '不是自增列'
SELECT * FROM sys.columns WHERE object_id=OBJECT_ID('表名') AND is_identity=1
10 判斷表中是否存在索引
if exists(select * from sysindexes where id=object_id('表名') and name='索引名')
print '存在'
else
print '不存在'
11 查看數據庫中對象
SELECT * FROM sys.sysobjects WHERE name='對象名' SELECT * FROM sys.sysobjects WHERE name='對象名'