[英]Why can't I add a column to an existing table with a checkConstraint that references other columns in SQL
I'm using SQL Server and am trying to add a column and a check constraint.我正在使用 SQL 服务器并尝试添加列和检查约束。 I've found that the following works:我发现以下工作:
ALTER TABLE table.column
ADD isTrue BIT
GO
ALTER TABLE table.column
ADD CONSTRAINT CK_table_isTrue CHECK ((isTrue = 1 AND column1 = 0 AND column2 = 0 AND column3 IS NULL) OR isTrue = 0)
However a less verbose way of writing this does not work:然而,一种不太冗长的写法是行不通的:
ALTER TABLE table.column
ADD isTrue BIT
CONSTRAINT CK_table_isTrue CHECK ((isTrue = 1 AND column1 = 0 AND column2 = 0 AND column3 IS NULL) OR isTrue = 0)
The following error is output:以下错误为 output:
Column CHECK constraint for column 'isTrue' references another column, table 'table'.列“isTrue”的列 CHECK 约束引用另一列,表“表”。
Looking at docs and SO I was unable to determine why this is the case查看文档,所以我无法确定为什么会这样
Your syntax is not quite right.你的语法不太正确。 A constraint that references multiple columns is a table constraint.引用多列的约束是表约束。 Your're trying to add a table constraint so you need a comma after the datatype definition for isTrue.您正在尝试添加表约束,因此在 isTrue 的数据类型定义后需要一个逗号。
ALTER TABLE table.column
ADD isTrue BIT,
CONSTRAINT CK_table_isTrue CHECK ((isTrue = 1 AND column1 = 0 AND column2 = 0 AND column3 IS NULL) OR isTrue = 0);
Without the comma SQL Server thinks you're trying to add a column constraint thus the error that you're referencing a different column.没有逗号 SQL 服务器认为您正在尝试添加列约束,因此您引用不同列的错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.