Add a column with a default and foreign key constraint

Add a column with a default and foreign key constraint

Every so often you may be presented with the requirement to add an additional column to one of your database tables. My experience, with SQL Server 2008 and above at least, is that Management Studio will not allow you to modify table structures via the GUI (backed up here and here) unless explicitly allowed via SSMS configuration options.

This is a good thing. It is turned off by default for a reason.

If you do not possess the skills to be able to perform structure changes via SQL, I wouldn’t want you in Management Studio in the first place.

Regardless, here is a quick snippet to add an additional currency column to a table with a default value of 1 and an FK constraint against the dbo.currencies table.

 
ALTER TABLE [dbo].[mytable]
ADD [currency_id] INT
CONSTRAINT [DF_mytable_currency_id] DEFAULT ((1)) NOT NULL,
CONSTRAINT [FK_mytable_currency_id] FOREIGN KEY ([currency_id]) 
  REFERENCES [dbo].[currencies] ([currency_id])

Enjoy!

Mike250

I'm an Australian Chief Analytics Officer passionate about data science, visual insights, and all things sportโ€”particularly cricket. An adventurer at heart, Iโ€™ve gone from abseiling cliffs to snorkeling in crystal-clear waters, sleeping in the wilds of Africa, and exploring destinations worldwide, with my latest trip taking me to Bali. When I'm not diving into data or analytics, I'm spending time with my three sons and two daughters, attempting to hit sixes for my local cricket club, reviewing chicken schnitzels or honing my craft around a coffee machine.

Related Posts
Leave a comment

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