Quantcast
Channel: How to add a column with a default value to an existing table in SQL Server? - Stack Overflow
Viewing all articles
Browse latest Browse all 91

Answer by magnus for Add a column with a default value to an existing table in SQL Server

$
0
0

There are 2 different ways to address this problem.Both adds a default value but adds a totally different meaning to the problem statement here.

Lets start with creating some sample data.

Create Sample Data

CREATE TABLE ExistingTable (ID INT)GOINSERT INTO ExistingTable (ID)VALUES (1), (2), (3)GOSELECT *FROM ExistingTable

enter image description here

1.Add Columns with Default Value for Future Inserts

ALTER TABLE ExistingTableADD ColWithDefault VARCHAR(10) DEFAULT 'Hi'GO

enter image description here

So now as we have added a default column when we are inserting a new record it will default it's value to 'Hi' if value not provided

INSERT INTO ExistingTable(ID)VALUES (4)GOSelect * from ExistingTableGO

enter image description here

Well this addresses our problem to have default value but here is a catch to the problem.What if we want to have default value in all the columns not just the future inserts???For this we have Method 2.

2.Add Column with Default Value for ALL Inserts

ALTER TABLE ExistingTableADD DefaultColWithVal VARCHAR(10) DEFAULT 'DefaultAll'WITH VALUESGOSelect * from ExistingTableGO

enter image description here

The following script will add a new column with a default value in every possible scenario.

Hope it adds value to the question asked.Thanks.


Viewing all articles
Browse latest Browse all 91

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>