采用以下示例表:
CREATE TABLE [dbo].[tbl_Example](
[PageID] [int] IDENTITY(1,1) NOT NULL,
[RequireLogin] [bit] NOT NULL,
[RequireAdmin] [bit] NOT NULL,
[HideIfLoggedIn] [bit] NOT NULL
)
如何重写上述内容以包括检查约束,如下所示:
[RequireAdmin]
错误,则强制[RequireLogin]
为错误(即仅允许[RequireAdmin]
为真< / strong>如果[RequireLogin]
True ,同时允许[RequireLogin]
True 且[RequireAdmin]
False [HideIfLoggedIn]
错误 [RequireLogin]
为真
答案 0 :(得分:9)
您通常在检查中执行嵌套的case语句,以使该类型的逻辑起作用。请记住,支票中的案例仍然必须是评估,因此需要采用
形式CHECK (case when <exp> then 1 end = 1).
查看您的确切要求,但似乎这也可行,并且可能更容易阅读:
CREATE TABLE [dbo].[tbl_Example]
(
[PageID] [int] IDENTITY(1,1) NOT NULL,
[RequireLogin] [bit] NOT NULL,
[RequireAdmin] [bit] NOT NULL,
[HideIfLoggedIn] [bit] NOT NULL
)
ALTER TABLE [dbo].[tbl_Example] ADD CONSTRAINT
[RequireAdmin] CHECK
((RequireAdmin = RequireLogin) OR
(RequireLogin=1));
ALTER TABLE [dbo].[tbl_Example] ADD CONSTRAINT
[HideIfLoggedIn] CHECK
((RequireLogin=1 AND HideIfLoggedIn=0) OR
(RequireLogin=0 AND HideIfLoggedIn=1) OR
(RequireLogin=0 AND HideIfLoggedIn=0))
答案 1 :(得分:2)
如果我有正确的代数:
alter table dbo.Example
add constraint RequireAdmin_RequireLogin_ck
check ( not ( RequireAdmin = 'true' and RequireLogin = 'false' ) ) ;
alter table dbo.Example
add constraint HideIfLoggedIn_RequireLogin_ck
check ( not ( HideIfLoggedIn = 'true' and RequireLogin = 'true' ) ) ;
请注意,这些检查约束是在表级别而不是列级别定义的,因为它们必须引用多个列。由于这个原因,RThomas的答案无效Transact-SQL!