Wednesday, 22 May 2019

Before Alter or Create Check if Exists Trigger, Stored Procedure, functions, Table, Columns MS SQL

If you're looking for the simplest way to check for a database object's existence before removing or alter it...

Trigger

IF OBJECT_ID('Trigger Name', 'TR') IS NOT NULL
BEGIN
DROP TRIGGER [dbo].[Trigger Name]
end

Table
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES 
           WHERE TABLE_NAME = 'Your Table')
BEGIN
    DROP TABLE dbo.Your Table
End

Stored Procedure

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Your SP Name]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[Your SP Name]

Functions

IF EXISTS (SELECT *
    FROM sys.objects
    WHERE object_id = OBJECT_ID(N'[dbo].[Your Function Name]') AND type IN ( N'FN', N'IF', N'TF', N'FS', N'FT' ))

  DROP FUNCTION [dbo].[Your Function Name]



New Column with If Exists

IF NOT EXISTS(
    SELECT *
    FROM sys.columns 
    WHERE Name      = N'Your Column Name'
      AND Object_ID = Object_ID(N'Table Name'))
BEGIN
    ALTER TABLE Table Name
    ADD Column Name int NULL
END

No comments:

Post a Comment