如何向已有的列添加默认值?

发布于 2024-09-05 23:11:37 字数 267 浏览 2 评论 0原文

我的 SQL Server 数据库中有一个现有列。我已经尝试了我能想到的一切,但无法将默认值添加到列中。在所有其他数据库中有效的是

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

如何在 SQL Server 中执行此操作?

我得到的确切语法错误是关键字“set”附近的语法不正确

I have an existing column in my SQL Server database. 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?

The error I get for that exact syntax is incorrect syntax near the keyword 'set'

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

抱猫软卧 2024-09-12 23:11:37

使用:

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

有关详细信息,请参阅:使用默认约束< /a>

Use:

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

For more info, see: Working with Default Constraints

风吹短裙飘 2024-09-12 23:11:37

如果您想更改现有列的默认值。您需要首先删除约束,然后重新添加约束,如下所示

ALTER TABLE <TABLE> 
DROP CONSTRAINT <CONSTRAINT NAME>

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

如果您没有表的约束详细信息,您可以使用以下查询

sp_helpconstraint <TABLE>

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>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文