Sunday, January 08, 2006

SQL Existence Check Statements

So as I was working with some SQL today, I realize that when it comes to writing deploy scripts and DDL scripts, it is useful to use these SQL check clauses to check for the existance of the object before dropping and recreating. Although these scripts might be obsolete with the advent of meta tables in later version of SQL, it's still useful as a reference.

--Checking Table Column
if exists (SELECT * FROM sysobjects o, syscolumns c WHERE o.name like 'TableName' AND c.name like 'ColumnName' AND o.id = c.id AND (o.type not in ('P', 'FN', 'TF', 'IF') OR (o.type in ('TF', 'IF') and c.number = 0)))

--Checking Stored Procedure
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ProcedureName]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)

--Checking Functions
if exists (select * from dbo.sysobjects WHERE id = object_id(N'[dbo].[FunctionName]') and xtype in (N'FN', N'IF', N'TF'))

--Checking Tables
if exists (select * from [dbo].sysobjects where id = object_id(N'[dbo].[TableName]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)

--Checking Views
if exists (select * from [dbo].sysobjects where id = object_id(N'[dbo].[ViewName]') and OBJECTPROPERTY(id, N'IsView') = 1)

No comments: