开发者

Create non-nullable column but populate existing NULLs with some given value

开发者 https://www.devze.com 2023-02-25 19:15 出处:网络
I want to add a new column \"CreatedBy\" to a table PerformanceData. I want this new column to be nnon-nullable, and I want existing NULLs to be populated as \'NA\'. This is how I am doing t开发者_开发

I want to add a new column "CreatedBy" to a table PerformanceData. I want this new column to be nnon-nullable, and I want existing NULLs to be populated as 'NA'. This is how I am doing t开发者_开发百科his right now. Do we have a better way?

ALTER TABLE PerformanceData ADD CreatedBy VARCHAR(50) NOT NULL 
CONSTRAINT DF1 DEFAULT('NA')   

ALTER TABLE PerformanceData DROP CONSTRAINT DF1

I create a DEFAULT constraint and drop it later, because I don't want values to be inserted by default in future.


It looks good for me. If you want another way, you can do it in three steps:

ALTER TABLE PerformanceData ADD CreatedBy VARCHAR(50) NULL 

UPDATE PerformanceData SET CreatedBy = 'NA'

ALTER TABLE PerformanceData ALTER COLUMN CreatedBy VARCHAR(50) NOT NULL


I'd do it your way in 2 steps with a default constraint.

0

精彩评论

暂无评论...
验证码 换一张
取 消