将可空列更改为具有默认值的 NOT NULL
我今天遇到一个旧表,其中有一个名为“Created”的日期时间列,它允许空值。现在,我想更改它,使其不为 NULL,并且还包含一个添加默认值 (getdate()) 的约束。
到目前为止,我已经得到了以下脚本,只要我事先清除了所有空值,该脚本就可以正常工作:
ALTER TABLE dbo.MyTable ALTER COLUMN Created DATETIME NOT NULL
有没有办法在 ALTER 语句上也指定默认值?
I came across an old table today with a datetime column called 'Created' which allows nulls. Now, I'd want to change this so that it is NOT NULL, and also include a constraint to add in a default value (getdate()).
So far I've got the following script, which works fine provided that I've cleaned up all the nulls beforehand:
ALTER TABLE dbo.MyTable ALTER COLUMN Created DATETIME NOT NULL
Is there any way to also specify the default value as well on the ALTER statement?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我认为您需要将其作为三个单独的语句来执行。我环顾四周,我所看到的一切似乎都表明,如果您要添加一列,则可以做到这一点,但如果您要更改一列,则不行。
I think you will need to do this as three separate statements. I've been looking around and everything I've seen seems to suggest you can do it if you are adding a column, but not if you are altering one.
您可能必须首先将所有为空的记录更新为默认值,然后使用 alter table 语句。
You may have to first update all the records that are null to the default value then use the alter table statement.
您需要执行两个查询:
一个 - 将默认值添加到所需的列
我想向 Column IsDeleted 添加默认值,如下所示:
Two - 将列值可为空更改为不为空
我想让 IsDeleted 列不为空
you need to execute two queries:
One - to add the default value to the column required
i want add default value to Column IsDeleted as below:
Two - to alter the column value nullable to not null
i want to make the column IsDeleted as not null
如果是 SQL Server,您可以在设计视图中的列属性上执行此操作。
试试这个:
If it's SQL Server, you can do it on the column properties within design view.
Try this:
试试这个
Try this