Little SQL Server Tricks: Add New Columns With Default Value and Foreign Key

So far, I used separate statements to add a new column to a table, set a default value and add a foreign key relation to another table. However, we can do these 3 steps in one single command:

1
2
3
4
5
ALTER TABLE [Table Name] ADD
    [New Column Name] [Column Type] 
    CONSTRAINT [Constraint Name Default Value] DEFAULT ([Default Value]) NOT NULL,
    CONSTRAINT [Constraint Name Foreign Key] FOREIGN KEY ([New Column Name]) 
    REFERENCES [Other Table] ([Foreign Id])

This little trick can save you a lot of typing and puts everything that belongs together in the same command. I got this trick from a very useful Stack Overflow answer by Steve.