简体   繁体   English

为什么我不能使用引用 SQL 中其他列的 checkConstraint 将列添加到现有表

[英]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.

相关问题 sql一个表的两列引用另一表的同一列 - sql Two columns of one table references to the same column of the other table 如何在sql的外部表中添加其他列? - How can I add other columns from a foreign table in the sql? 将基于其他列的计算的列添加到 SQL Server 中的现有表 - Add a column based on calculation from other columns to an existing table in SQL Server 如何将一列添加到 SQL 表中,该列是其他两列的乘积? - How to add a column to an SQL table that is a multiplication of two other columns? 如何在 SQL 中添加一列并在单个查询中同时基于其他列设置其值? - How can i add a column in SQL and set its values based on other columns at the same time in a single query? 无法将列添加到现有表 - Can not add a column to existing table 如果所有列都可以为空并且不创建唯一索引但我可以添加约束,我如何在现有的 oracle sql 表中实现唯一性 - how can i make uniqueness in existing oracle sql table if all columns are nullable and also not creating unique index but i can add constraint 如何将一列添加到表中,它结合了其他列中的字符串? - How to I add a column to a table, that combines strings from other columns? T-SQL在现有表中添加新列,并从另一个现有列填充值 - T-SQL Add new column in existing table and fill with value from two another existing column SQL Server - 如果存在于其他表中,则更改列? - SQL Server - change column if existing in other table?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM