Friday, February 29, 2008

Check for existence of DB objects

Some queries I find useful to add before the Create/Alter Statements in SQL Server.

--Constraints
IF EXISTS(
SELECT NULL FROM INFORMATION_SCHEMA.Constraint_column_usage
where table_name ='MyTable'
and constraint_name = 'FK_COl1')

--Check existence of stored_proc
IF EXISTS (SELECT NULL
FROM information_schema.routines r
WHERE r.specific_schema = 'dbo'
AND r.specific_name = 'MyProc')
--Check column exists
IF NOT EXISTS (
SELECT NULL
FROM information_schema.columns
where column_name='Col1'
AND table_name ='MyTable'
and table_schema='dbo')

--Check for description
IF not EXISTS(
SELECT NULL from sys.all_objects ao
INNER JOIN sys.extended_properties ep on ao.object_id = ep.major_id and ep.name ='MS_Description'
where ao.name ='FK_key_name')