1. 程式人生 > 實用技巧 >if exists用法(判斷物件的用法)

if exists用法(判斷物件的用法)

1 判斷資料庫是否存在
if exists (select * from sys.databases where name = ’資料庫名’) 
drop database [資料庫名]
2 判斷表是否存在
if exists (select * from sysobjects where id = object_id(N’[表名]’) and OBJECTPROPERTY(id, N’IsUserTable’) = 1) 
drop table [表名]
3 判斷儲存過程是否存在
if exists (select * from sysobjects where id = object_id
(N’[儲存過程名]’) and OBJECTPROPERTY(id, N’IsProcedure’) = 1) drop procedure [儲存過程名] 4 判斷臨時表是否存在 if object_id(’tempdb..#臨時表名’) is not null drop table #臨時表名 5 判斷檢視是否存在 --SQL Server 2000 IF EXISTS (SELECT * FROM sysviews WHERE object_id =[dbo].[檢視名]--SQL Server 2005 IF EXISTS (SELECT * FROM sys.views WHERE
object_id =[dbo].[檢視名]--SQL Server 2000 IF EXISTS (SELECT * FROM sysviews WHERE object_id =[dbo].[檢視名]--SQL Server 2005 IF EXISTS (SELECT * FROM sys.views WHERE object_id =[dbo].[檢視名]6 判斷函式是否存在 -- 判斷要建立的函式名是否存在 if exists (select * from dbo.sysobjects where id = object_id(N’[dbo].[函式名]’) and xtype in
(N’FN’, N’IF’, N’TF’)) drop function [dbo].[函式名] -- 判斷要建立的函式名是否存在 7 獲取使用者建立的物件資訊 SELECT [name],[id],crdate 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=’列名’) alter table 表名 drop column 列名9 判斷列是否自增列 if columnproperty(object_id(’table’),’col’,’IsIdentity’)=1 print ’自增列’ else print ’不是自增列’ 10 判斷表中是否存在索引 if exists(select * from sysindexes where id=object_id(’表名’) and name=’索引名’) print ’存在’ else print ’不存在11 檢視資料庫中物件 SELECT * FROM sys.sysobjects WHERE name=’物件名’