How to alter table add column with named default constraint and named foreign key constraint?

Sql Server

Sql Server Problem Overview


I have two existing tables (TableA and TableB) and I need to add a new column to TableA that has a foreign key to TableB and has a default value that is not null... and both these constraints need to be named. How can I do this?

Sql Server Solutions


Solution 1 - Sql Server

Adding both constraints in one statement wasn't as easy as I thought it would be and there didn't seem to be many examples out there (at least I wasn't able to find any very easily), so I thought I'd share how I did it here and maybe someone can suggest a better way?

ALTER TABLE [table name] ADD
    [New Column Name] [Column Type] 
    CONSTRAINT [constraint name] DEFAULT ([default value]) NOT NULL,
    CONSTRAINT [constraint name] FOREIGN KEY ([New Column Name]) 
    REFERENCES [Other Table] ([Foreign ID])

Example:

ALTER TABLE tableA ADD
    myNewColumn BIGINT 
    CONSTRAINT myNamedConstraint_df default (1) NOT NULL,
    CONSTRAINT myNamedConstraint_fk FOREIGN KEY (myNewColumn)
    REFERENCES tableB (tableBPrimaryKeyID)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSteveView Question on Stackoverflow
Solution 1 - Sql ServerSteveView Answer on Stackoverflow