更改表格中的列类型

时间:2014-07-08 08:38:26

标签: sql database oracle triggers oracle10g

我在Oracle中有一个名为deal的数据表有四列:
DealID:(PK)
LegID
OrigID
说明

问题是,如果我想插入一个描述= A的交易,LegID和OrigID属性必须是唯一的,否则,没有问题。我该怎么做这个检查?插入后我曾想过触发器。还有更多解决方案吗?

提前致谢!!

1 个答案:

答案 0 :(得分:0)

您需要基于功能的唯一索引:

create table tt (
  DealID number(10) primary key,
  LegID number(10),
  OrigID number(10),
  Description varchar2(200 char)
);
create unique index tt_leg_orig_dscr_uk on tt (
  case when description = 'A' then description end,
  case when description = 'A' then legid end,
  case when description = 'A' then origid end
);

insert into tt values (1, 1, 1, 'A');
1 row(s) inserted.

insert into tt values (2, 1, 1, 'A');
ORA-00001: unique constraint (XXXXX.TT_LEG_ORIG_DSCR_UK) violated

insert into tt values (2, 1, 2, 'A');
1 row(s) inserted.

select * from tt;
DEALID  LEGID   ORIGID  DESCRIPTION
-----------------------------------
    1       1        1           A
    2       1        2           A
2 rows returned in 0.01 seconds

insert into tt values (3, 1, 1, 'B');
1 row(s) inserted.

insert into tt values (4, 1, 1, 'B');
1 row(s) inserted.

select * from tt order by 1;

DEALID  LEGID   ORIGID  DESCRIPTION
-----------------------------------
     1      1        1           A
     2      1        2           A
     3      1        1           B
     4      1        1           B
4 rows returned in 0.01 seconds 

正如您所看到的,唯一索引仅适用于包含说明=' A'的记录,它允许为不同的描述提供非唯一记录。

相关问题