我需要有关此检查约束的帮助,我收到以下错误消息:"消息102,级别15,状态1,行14'='附近的语法不正确."
或许我应该问的问题是,使用检查约束是否可行
我想要实现的是:如果InformationRestricted为True,则InformationNotRestricted不能为true且InformationRestrictedFromLevel1,InformationRestrictedFromLevel2,InformationRestrictedFromLevel3,InformationRestrictedFromLevel4,InformationRestrictedFromLevel5不能为true
我不是试图为列分配值,只是在InformationRestricted为True时尝试确保列的值= 0(即为false)
这是脚本:
CREATE TABLE EmployeeData
(FirstName varchar(50),
Last Name varchar(50),
Age int,
Address varchar(100),
InformationRestricted bit,
InformationNotRestricted bit,
InformationRestrictedFromLevel1 bit,
InformationRestrictedFromLevel2 bit
InformationRestrictedFromLevel3 bit
InformationRestrictedFromLevel4 bit
InformationRestrictedFromLevel5 bit);
ALTER TABLE EmployeeData ADD CONSTRAINT ck_EmployeeData
CHECK (CASE WHEN InformationRestricted = 1 THEN InformationNotRestricted = 0 --InformationRestricted is true, InformationNotRestricted is false
AND( InformationRestrictedFromLevel1 = 0 --is false
OR InformationRestrictedFromLevel2 = 0 --is false
OR InformationRestrictedFromLevel3 = 0 --is false
OR InformationRestrictedFromLevel4 = 0 --is false
OR InformationRestrictedFromLevel5 = 0)); --is false
Run Code Online (Sandbox Code Playgroud)
甲CASE 表达的东西,返回一个特定的数据类型(由每个不同的数据类型来确定的类型的值THEN子句).
SQL Server不具有逻辑数据类型,所以你不能返回一个比较操作的结果.
尝试在WHEN子句中添加其他比较,并且THEN如果要允许或不允许结果(分别),则返回s或1或0.然后将整体结果与1进行比较.
我不能完全解析你的情况,但是像:
CHECK(CASE WHEN InformationRestricted = 1 THEN
CASE WHEN InformationNotRestricted = 0 AND
(InformationRestrictedFromLevel1 = 0 --is false
OR InformationRestrictedFromLevel2 = 0 --is false
OR InformationRestrictedFromLevel3 = 0 --is false
OR InformationRestrictedFromLevel4 = 0 --is false
OR InformationRestrictedFromLevel5 = 0)
THEN 1
ELSE 0
END
--Other conditions?
END = 1)
Run Code Online (Sandbox Code Playgroud)
我的困惑是,虽然你想要检查一个且只有一个InformationRestrictedFromXXX列是一个,但我有.事实上,从一般描述(不知道更多关于你的问题域),我可能只是创建了一个InformationRestrictionLevel类型的列int,其0含义不受限制,更高的值表示它受限制的级别.