简体   繁体   English

如何为现有列添加默认值?

[英]How to add a default value to an already existing column?

I have an existing column in my SQL Server database. 我的SQL Server数据库中有一个现有的列。 I have tried about everything I can think of but can not get a default value to be added to the column. 我已经尝试了所有我能想到的事情,但是无法将默认值添加到该列中。 What works in every other database is 在其他所有数据库中有效的是

alter table mytable 
  alter column mycolumn set default(now()) --mycolumn is a datetime

How do I do this in SQL Server? 如何在SQL Server中执行此操作?

The error I get for that exact syntax is incorrect syntax near the keyword 'set' 我得到的确切语法incorrect syntax near the keyword 'set'语法incorrect syntax near the keyword 'set'

Use: 使用:

ALTER TABLE dbo.mytable
ADD CONSTRAINT def_mycolumn DEFAULT GETDATE() FOR mycolumn

For more info, see: Working with Default Constraints 有关更多信息,请参见: 使用默认约束

If you want to change the default value of an already existing column. 如果要更改现有列的默认值。 You need to first drop the constraint and then add the constraint all over again as below 您需要先删除约束,然后再次如下所示重新添加约束

ALTER TABLE <TABLE> 
DROP CONSTRAINT <CONSTRAINT NAME>

ALTER TABLE <TABLE> 
ADD CONSTRAINT <CONSTRAINT NAME> DEFAULT <VALUE> for <COLUMN>

If you are not having the Constraint details of the table, you can use the below query 如果您没有该表的约束详细信息,则可以使用以下查询

sp_helpconstraint <TABLE>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM