更改 SQL Server 中的列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13294468/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 12:02:02  来源:igfitidea点击:

Alter column in SQL Server

sqlsql-server-2008

提问by GenZiy

What is correct syntax for an ALTERstatement 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' 附近的语法不正确。

回答by Taryn

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 nullvalues in your table which is causing the alter of the column to not nullto fail. If that is the case, then you should run an UPDATEfirst. Your script will be:

根据您的一些评论,我猜测null您的表中可能已经有值,这会导致更改列not null失败。如果是这种情况,那么您应该先运行UPDATE。您的脚本将是:

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

See SQL Fiddle with demo

请参阅带有演示的 SQL Fiddle

回答by Prakash

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

回答by user3262848

To set a default value to a column, try this:

要为列设置默认值,请尝试以下操作:

ALTER TABLE tb_TableName
ALTER COLUMN Record_Status SET DEFAULT 'default value'