日期:2014-05-17  浏览次数:21020 次

关于两个不是主键的字段联合是唯一的特殊问题 急求
问题 数据库限制字段 两个字段 type 和 num。一般情况下num没有值,当num没有值的时候随便插入表数据。但是,当num有值的时候,就要和type联合起来,判断是不是 type+num是否唯一。(type+null 这种是可以重复的)
例如 ab , null 可以继续添加记录 ab null 
但是如果记录里面有了 ab 123 那就不能再添加 ab 123了。
怎么写限制字段 unique么? 好像是不行。 
ps: ab是不会有null情况出现的
急求

------解决方案--------------------
用触发器

create or replace trigger tr_test_unique
before insert on test_unique 
for each row
declare
vint number;
begin
if :new.num is not null then
select count(*) into vint from test_unique where type=:new.type and num=:new.num;
if vint>0 then
raise_application_error(-20001,'type与num联合不能重复');
end if;
end if;
end;