Thursday, September 27, 2012

Various object existence checks in Sql Server

Here are the basic scripts you need to check for the existence of various objects in a Sql Server database (tables, columns, etc)

Check if Database exists:

IF  EXISTS (SELECT name FROM sys.databases WHERE name = N'DataBaseName')
begin

-- Database Exists

end

Check if table exists:

IF  EXISTS (SELECT * FROM sys.objects 
WHERE object_id = OBJECT_ID(N'[schema].[tableName]')
AND type in (N'U'))
BEGIN
    --Table exists
END

Check if foreign key exists:

IF  EXISTS (SELECT * FROM sys.foreign_keys
WHERE object_id = OBJECT_ID(N'[schema].[foreignKeyName]')
AND parent_object_id = OBJECT_ID(N'[schema].[tableName]'))
Begin
    --foreign key exists
End

Check if index exists:

IF  EXISTS (SELECT * FROM sys.indexes
WHERE object_id = OBJECT_ID(N'[schema].[tableName]')
AND name = N'IndexName')Begin
--Index exists
END

Check if view exists:

IF  EXISTS (SELECT * FROM sys.views 
WHERE object_id = OBJECT_ID(N'[schema].[viewName]'))
Begin
--View exists
END

Check if column exists:

if Exists(select * from sys.columns 
where Name = N'columnName'
and Object_ID = Object_ID(N'tableName'))

begin

    -- Column Exists

end

Check if Stored Proc exists:

IF  EXISTS (SELECT * FROM sys.objects 
WHERE object_id = OBJECT_ID(N'[Schema].[StoredProcName]')
AND type in (N'P', N'PC'))
begin

-- Stored Proc exists

end

Check if Function exists:

IF  EXISTS (SELECT * FROM sys.objects 
WHERE object_id = OBJECT_ID(N'[Schema].[FunctionName]')
AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))

begin

-- Function Exists

end

No comments: