可以在创建表时创建约束,也可以通过更改现有表来创建约束。
创建一个新表
create table SomeTable(
Col_1 varchar(20),
Col_2 varchar(20),
constraint unq_SomeTable_c1_c2 unique(Col_1, Col_2));
go
更改现有表
alter table SomeTable
add
constraint unq_SomeTable_c1_c2 unique(Col_1, Col_2);
如果尝试重复插入,错误消息将如下所示
Msg 2627, Level 14, State 1, Line 7502
Violation of UNIQUE KEY constraint 'unq_SomeTable_c1_c2'. Cannot insert duplicate key in object 'dbo.SomeTable'. The duplicate key value is (ABC, DEF).
The statement has been terminated.
[编辑] 为了确保列的顺序无关紧要,我创建了一个 TRIGGER,它在 INSERT 或 UPDATE 之后运行。错误信息可以随意更改。
create trigger trg_SomeTable_unq_c2c1_ins_upd on SomeTable
after insert, update
as
if exists(select 1
from SomeTable st join inserted i on st.Col_2=i.Col_1
and st.Col_1=i.Col_2)
rollback transaction;
go
测试用例
insert SomeTable(Col_1, Col_2) values
('ABC', 'DEF'),
('QER', 'ZXC'),
('ASD', 'VBN');
insert SomeTable(Col_1, Col_2) values
('DEF', 'ABC');
输出
(3 row(s) affected)
Msg 3609, Level 16, State 1, Line 7514
The transaction ended in the trigger. The batch has been aborted.