Quantcast
Viewing all articles
Browse latest Browse all 91

Answer by ishant kaushik for How to add a column with a default value to an existing table in SQL Server?

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

Let's 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

Image may be NSFW.
Clik here to view.
enter image description here

1. Add Columns with Default Value for Future Inserts

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

Image may be NSFW.
Clik here to view.
enter image description here

So now, as we have added a default column when we are inserting a new record, it will default its value to 'Hi' if the value is not provided.

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

Image may be NSFW.
Clik here to view.
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 a 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

Image may be NSFW.
Clik here to view.
enter image description here

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


Viewing all articles
Browse latest Browse all 91

Trending Articles



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