问题 数据库限制字段 两个字段 type 和 num。一般情况下num没有值,当num没有值的时候随便插入表数据。但是,当num有值的时候,就要和type联合起来,判断是不是 type+num是否唯一。(type+null 这种是可以重复的)
例如 ab , null 可以继续添加记录 ab null
但是如果记录里面有了 ab 123 那就不能再添加 ab 123了。
怎么写限制字段 unique么? 好像是不行。
ps: ab是不会有null情况出现的
急求
例如 ab , null 可以继续添加记录 ab null
但是如果记录里面有了 ab 123 那就不能再添加 ab 123了。
怎么写限制字段 unique么? 好像是不行。
ps: ab是不会有null情况出现的
急求
SQL> create table table1(col1 char(2),col2 char(2));表已创建。SQL> create unique index idx_1 on table1(col1,col2);索引已创建。SQL> insert into table1 values(null,'1');已创建 1 行。SQL> commit;提交完成。SQL> insert into table1 values('1','1');已创建 1 行。SQL> commit;提交完成。SQL> insert into table1 values(null,null);已创建 1 行。SQL> commit;提交完成。SQL> insert into table1 values('1',null);已创建 1 行。SQL> commit;提交完成。SQL> select * from table1;COL1 COL2
---- ----
1
1 11SQL> insert into table1 values('1'
2 ,null);
insert into table1 values('1'
*
第 1 行出现错误:
ORA-00001: 违反唯一约束条件 (SYS.IDX_1)
SQL>
COL1 COL2
---- ----
1
1
1 3
1 2
这些都可以添加进去,
但是,
insert into table1 values('1' ,'3') 就要求报错,不允许插入了。因为要插入的COL2是3,要和COL1联合检验一下。发现已经有 ‘1’ ‘3’了 就不允许插入了再请教
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;
insert into test (COL1) values ('aaa');
会报错。
Name Type Nullable Default Comments
---- ------------ -------- ------- --------
TYPE VARCHAR2(20) Y
NUM INTEGER Y SQL> select * from test_unique;TYPE NUM
-------------------- ---------------------------------------
12
12 2
12 3
1
1
1
1
1 2
3 3
3
aaa 11 rows selectedSQL> insert into test_unique(type) values('aaaa');1 row insertedSQL> insert into test_unique(type,num) values('ddd',1);1 row insertedSQL> insert into test_unique(type,num) values('ddd',1);insert into test_unique(type,num) values('ddd',1)ORA-20001: type与num联合不能重复
ORA-06512: 在 "TEST01.TR_TEST_UNIQUE", line 7
ORA-04088: 触发器 'TEST01.TR_TEST_UNIQUE' 执行过程中出错SQL>