如何编写sql来设置sql server 2005中更改列的默认值?

发布于 2024-08-03 22:59:53 字数 148 浏览 2 评论 0原文

我有一个表 [Product],其列 [CreateTime] datetime null,并且已经有一些数据。

如何将 [CreateTime] 列的默认值设置为 getdate(),并使新添加的数据的 [CreateTime] 列具有默认值 getdate()。

I have a table [Product] with a column [CreateTime] datetime null, and is has some data already.

How can I set the column [CreateTime] 's default value to getdate(), and make the new added data to have a default value getdate() for column [CreateTime].

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

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

发布评论

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

评论(1

紫南 2024-08-10 22:59:53

您无法更改默认值 - 您需要先删除它,然后重新创建它。

为了删除它,您需要知道它的名称,然后使用

ALTER TABLE dbo.Product
  DROP CONSTRAINT yourOldDefaultConstraint

完成后,您可以添加一个新的默认约束,并且为了将其应用到现有行,请使用“WITH VALUES”部分:

ALTER TABLE dbo.Product
   ADD CONSTRAINT NewDefaultConstraintName
   DEFAULT GetDate() FOR CreateTime WITH VALUES

哎呀- 抱歉,“WITH VALUES”似乎仅在您创建表时创建 DEFAULT 约束或者添加列时才起作用 - 它似乎不会应用于现有列。

在这种情况下,您只需在 ALTER TABLE 语句后添加如下内容:

UPDATE dbo.T_Product
SET CreateTime = GETDATE()
WHERE CreateTime IS NULL

这也应该可以解决问题!

马克

You cannot change a default - you will need to first drop it, and then recreate it.

In order to drop it, you need to know its name, and then use

ALTER TABLE dbo.Product
  DROP CONSTRAINT yourOldDefaultConstraint

Once you've done that, you can add a new default constraint, and in order to apply it to existing rows, use the "WITH VALUES" part:

ALTER TABLE dbo.Product
   ADD CONSTRAINT NewDefaultConstraintName
   DEFAULT GetDate() FOR CreateTime WITH VALUES

Oops - sorry, the "WITH VALUES" only seems to work if you create a DEFAULT constraint at the time you create the table, or if you add the column - it doesn't seem to get applied to an existing column.

In this case you would just have to follow your ALTER TABLE statement with something like this:

UPDATE dbo.T_Product
SET CreateTime = GETDATE()
WHERE CreateTime IS NULL

That should do the trick, too!

Marc

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