0 Comments

If you want to add a column to a table in SQL Server and the column should contain multiple constraints, you can declare these constraints inline in one statement by separating them with spaces.

if not exists (select 1 from sys.columns where name = 'MyColumn1' and Object_ID = Object_ID('dbo.MyTable1'))
begin 
    alter table dbo.MyTable1 with nocheck add MyTable2Id int not null 
        constraint FK_dbo_MyTable1_MyTable2Id foreign key references dbo.MyTable2Id(Id)
        constraint DF_dbo_MyTable1_MyTable2Id default(1)
end
go

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts