[英]Alter column in SQL Server
What is correct syntax for an ALTER
statement to add a default value to an existing column? ALTER
语句向现有列添加默认值的正确语法是什么?
I can add new column with no errors: 我可以添加没有错误的新列:
ALTER TABLE tb_TableName ADD Record_Status varchar(20)
But If I try to alter existing column to apply default value by using the following statement: 但是,如果我尝试使用以下语句更改现有列以应用默认值:
ALTER TABLE tb_TableName
ALTER COLUMN Record_Status VARCHAR(20) NOT NULL DEFAULT ''
or 要么
ALTER TABLE tb_TableName
ALTER Record_Status VARCHAR(20) NOT NULL DEFAULT ''
I have get an error: 我收到一个错误:
Incorrect syntax near 'Record_Status'. 'Record_Status'附近的语法不正确。
I think you want this syntax: 我想你想要这个语法:
ALTER TABLE tb_TableName
add constraint cnt_Record_Status Default '' for Record_Status
Based on some of your comments, I am going to guess that you might already have null
values in your table which is causing the alter of the column to not null
to fail. 根据您的一些注释,我猜测您的表中可能已经存在null
值,导致列的更改not null
失败。 If that is the case, then you should run an UPDATE
first. 如果是这种情况,那么您应该首先运行UPDATE
。 Your script will be: 你的脚本将是:
update tb_TableName
set Record_Status = ''
where Record_Status is null
ALTER TABLE tb_TableName
ALTER COLUMN Record_Status VARCHAR(20) NOT NULL
ALTER TABLE tb_TableName
ADD CONSTRAINT DEF_Name DEFAULT '' FOR Record_Status
Try this one. 试试这个吧。
ALTER TABLE tb_TableName
ALTER COLUMN Record_Status VARCHAR(20) NOT NULL
ALTER TABLE tb_TableName
ADD CONSTRAINT DEF_Name DEFAULT '' FOR Record_Status
To set a default value to a column, try this: 要为列设置默认值,请尝试以下操作:
ALTER TABLE tb_TableName
ALTER COLUMN Record_Status SET DEFAULT 'default value'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.