用Case检查约束条件

时间:2016-08-03 08:53:00

标签: sql-server constraints

尝试将检查约束添加到下表中:

CREATE TABLE TEST_A 
(
     NAME VARCHAR(55), 
     Country VARCHAR(50)
)

ALTER TABLE TEST_A 
  ADD CONSTRAINT CK_GBR_TO_IND
      CHECK (Country = CASE WHEN 'GBR' THEN 'IND' ELSE COUNTRY END);

我收到以下错误:

  

Msg 4145,Level 15,State 1,Line 2
  在预期条件的上下文中指定的非布尔类型的表达式,接近' THEN'。

2 个答案:

答案 0 :(得分:2)

尝试使用触发器.. You Can't use Check Constraint to change values ...

create trigger trg_test
on yourtable
instead of insert 
as
Begin

insert into yourtable--assuming it has only country column
select case when country='GBR' then 'IND'
else country end
from Inserted 

end

答案 1 :(得分:1)

ALTER TABLE TEST_A ADD CONSTRAINT CK_GBR_TO_IND
CHECK (Country IN('GBR', 'IND'));