SQL SERVER – Using CASE Expression in Default Value

It is not possible to use CASE Expression in Default Values when you add a new column. I hope this answers the question. However, there is a workaround. Let us learn that today.

Using case expression in default value.

After reading the previous blog post SQL SERVER – Altering Column – From NULL to NOT NULL, I received a few emails and comments about whether the new column is populated based on the condition. Actually, it is not possible.

The workaround contains two steps.

Step 1: Add Column

ALTER TABLE TableName
ALTER COLUMN ColumnName VARCHAR(100) NOT NULL DEFAULT ''

Step 2: Apply Condition Update

UPDATE TableName
SET ColumnName = 'FirstVal'
WHERE Col1 = 1;
UPDATE TableName
SET ColumnName = 'SecondVal'
WHERE Col1 = 2;
--... and so on...

Well, that’s it. Sometimes the question is complex but the answer is simple. I hope you enjoyed this simple blog post about case expression.

If you liked this blog, please do not forget to subscribe to my YouTube Channel – SQL in Sixty Seconds.

Here are my few recent videos and I would like to know what is your feedback about them.

Published by Pinal Dave on SQLAuthority. More of my work at pinaldave.com.

SQL CASE, SQL Scripts, SQL Server, SQL Table Operation
Previous Post
SQL SERVER – Find Instance Name for Availability Group Listener
Next Post
Experience – My Very First YouTube Live

Related Posts

Leave a Reply

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

Fill out this field
Fill out this field
Please enter a valid email address.