2016-08-03 60 views
0

尝试将检查约束添加下表:检查约束与案例当

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
An expression of non-boolean type specified in a context where a condition is expected, near 'THEN'.

+1

您无法更改要插入的值在检查约束。您可能需要改为使用触发器。 –

+0

为什么不使用触发器? – Sami

+0

如果country = GBR,则可以在插入后使用触发器,然后设置country = IND – Sami

回答

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 
+0

失败,出现以下错误:消息4145,级别15,状态1,行8 在接近')'的预期条件的上下文中指定的非布尔类型的表达式。 – Sharktooth

+0

@Sharktooth:看触发器的例子 – TheGameiswar

+0

触发器是唯一的方法。 – Sharktooth

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

但是,只有当插入的行的GBR为IND时,所有其他记录集应该照常插入时,我想更改记录值。 – Sharktooth

+0

@Sharktooth:你是否想要防止有GBR和IND的记录 – TheGameiswar

+0

@TheGameiswar否,如果插入的行有Country = GBR,则插入'IND',而不是如何工作。 – Sharktooth