問(wèn)題描述
我正在嘗試使用以下 T-SQL 向 SQL Server 中的現(xiàn)有字段添加默認(rèn)約束:
I'm trying to add a default constraint to an existing field in SQL Server using the following T-SQL:
alter table Extra 添加約束 DF_Extra_ExternalRef DEFAULT ('*') for帶值的外部引用
alter table Extra add constraint DF_Extra_ExternalRef DEFAULT ('*') for ExternalRef with values
這會(huì)添加默認(rèn)約束,但無(wú)法使用空值更新現(xiàn)有記錄.
This adds the default constraint but fails to update existing records with null values.
我使用的是 SQL Server 2005.
I'm using SQL Server 2005.
推薦答案
我只見(jiàn)過(guò) WITH VALUES
在添加新列時(shí)使用這種方式(這是 所有記錄).如果您要向現(xiàn)有列添加約束,我認(rèn)為 WITH VALUES
是無(wú)操作的.因此:
I've only ever seen WITH VALUES
used this way when adding a new column (and this is all that is documented). If you're adding a constraint to an existing column, I think WITH VALUES
is a no-op. Therefore:
ALTER TABLE dbo.Extra ADD CONSTRAINT DF_Extra_ExternalRef
DEFAULT ('*') FOR ExternalRef;
UPDATE dbo.Extra SET ExternalRef = '*' WHERE ExternalRef IS NULL;
這篇關(guān)于向具有值的現(xiàn)有字段添加默認(rèn)約束的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!