You are here: Home > Technical Articles > MS SQL Server - Script for creating foreign key constraint if it does not already exist

MS Sql Server - Script for creating a foreign key constraint if it does not exist



SQL Script looks for foreign key constraint and creates it only if does not already exist.

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'FK_type_ID') AND type = 'F')
BEGIN
    ALTER TABLE "invoice" WITH CHECK ADD CONSTRAINT "FK_type_ID"
        FOREIGN KEY ("type_ID")
        REFERENCES "invoice_type"("type_ID")
            ON UPDATE NO ACTION
            ON DELETE NO ACTION

END
GO


Published On: 02 Aug 2009