1. Check If Column Exists in Table:
IF EXISTS(SELECT 1 FROM sys.columns
WHERE Name = N'columnName'
AND Object_ID = Object_ID(N'schemaName.tableName'))
BEGIN
-- Column Exists
END
2. Check If Table Exists
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = N'Customers')
BEGIN
PRINT 'Table Exists'
END
3. Check If Stored Procedure Exists in SQL
IF EXISTS ( SELECT *
FROM sysobjects
WHERE id = object_id(N'[dbo].[MyProc]')
and OBJECTPROPERTY(id, N'IsProcedure') = 1 )
BEGIN
--DROP PROCEDURE [dbo].[MyProc]
END
4. Check If User-Defined Function Exists in SQL
IF EXISTS (SELECT *
FROM sys.objects
WHERE object_id = OBJECT_ID(N'[dbo].[foo]')
AND type IN ( N'FN', N'IF', N'TF', N'FS', N'FT' ))
Begin
--DROP FUNCTION [dbo].[foo]
End
GO
IF EXISTS(SELECT 1 FROM sys.columns
WHERE Name = N'columnName'
AND Object_ID = Object_ID(N'schemaName.tableName'))
BEGIN
-- Column Exists
END
2. Check If Table Exists
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = N'Customers')
BEGIN
PRINT 'Table Exists'
END
3. Check If Stored Procedure Exists in SQL
IF EXISTS ( SELECT *
FROM sysobjects
WHERE id = object_id(N'[dbo].[MyProc]')
and OBJECTPROPERTY(id, N'IsProcedure') = 1 )
BEGIN
--DROP PROCEDURE [dbo].[MyProc]
END
4. Check If User-Defined Function Exists in SQL
IF EXISTS (SELECT *
FROM sys.objects
WHERE object_id = OBJECT_ID(N'[dbo].[foo]')
AND type IN ( N'FN', N'IF', N'TF', N'FS', N'FT' ))
Begin
--DROP FUNCTION [dbo].[foo]
End
GO
No comments:
Post a Comment