基于其他列的约束

Arc*_*l33 8 sql-server constraint sql-server-2008-r2

是否可以根据行中的其他值来限制列中允许的值?

例如,我的表:

ID  Test_mode  Active
--  ---------  ------
1   1          Null
2   0          1
3   1          0
Run Code Online (Sandbox Code Playgroud)

有没有办法要么改变的值Test_mode0如果1插入Active

或者

如果Test_mode是 1 不允许插入/更新Active

或者

如果Test_mode是 1 并Active尝试插入/更新,则抛出某种错误。

Active只能是 NULL, 1, 0, AND only 1 with Test_modeas 0.

我希望这是有道理的,如果没有让我知道,我会更新问题。

Kin*_*hah 8

首先,欢迎来到 dba.stackexchange.com 并感谢您的帖子!

是否可以根据行中的其他值来限制列中允许的值。

是的,使用此处描述的CHECK CONSTRAINTS

例子 :

create table myTable (ID int identity(1,1)
                        , Test_mode int
                        , Active int 
                        )
go

-- Active can only be NULL, 1, 0, AND only 1 with Test_mode as 0.
ALTER TABLE myTable WITH CHECK ADD 
   CONSTRAINT ck_active CHECK (active IS NULL OR active IN (1, 0)) 
   go

-- some test data
insert into myTable (test_mode, Active) values (1, null)
insert into myTable (test_mode, Active) values (0, null)
insert into myTable (test_mode, Active) values (1, 0)
insert into myTable (test_mode, Active) values (0, 1)
insert into myTable (test_mode, Active) values (1, 1)

select * from myTable

-- Is there a way to either change the value of Test_mode to 0 if a 1 is inserted into Active

update myTable
set Test_mode = case when Active = 1 then  0
        else Test_mode 
        end
where Active = 1
Run Code Online (Sandbox Code Playgroud)

如果Test_mode为 1,则不允许插入/更新 Active -- 或 -- 如果 Test_mode 为 1 并尝试插入/更新 Active,则抛出某种错误。

按照此处所述使用 TRY/CATCH