我需要有关此检查约束的帮助,我收到以下错误消息:“消息102,级别15,状态1,行14 '='附近的语法不正确。“
或许我应该问的问题是,是否可以使用检查约束
我想要实现的是:如果InformationRestricted为True,则InformationNotRestricted不能为true且InformationRestrictedFromLevel1,InformationRestrictedFromLevel2,InformationRestrictedFromLevel3,InformationRestrictedFromLevel4,InformationRestrictedFromLevel5不能为真
我没有尝试为列分配值,只是在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
答案 0 :(得分:6)
CASE
表达式是返回特定数据类型的值(由每个THEN
子句的各种数据类型确定的类型)。
SQL Server 没有布尔数据类型,因此您无法返回比较操作的结果。
尝试在WHEN
子句中添加其他比较,并使THEN
返回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)
我的困惑是,虽然你想检查一个InformationRestrictedFromXXX
列中只有一个是一个,但我确实会这样。事实上,从一般描述(不了解您的问题域的更多信息),我可能刚刚创建了InformationRestrictionLevel
类型int
,其中0
意味着不受限制,和更高的值表示它受限制的级别。
答案 1 :(得分:3)
您似乎没有使用case
关闭end
。使用案例的检查约束的基本格式是:
check(case when <condition> then 1 else 0 end = 1)
如果您嵌套多个案例,请务必将案例数与结束次数相匹配:
check
(
1 =
case
when <condition> then
case
when <condition> then 1
else 0
end
else 0
end
)
使用相同的缩进格式化相同case
的所有元素可能会有很大的帮助。