如何允许 oracle table 列在列中有多个行但只有相同的值。使用约束

How to allow oracle table column to have multiple rows in column but sames values only. Using Constraints

如何允许 oracle table 列在列中有多个行但只有相同的值。

    Create Table test ( col int);


    case - I
    insert into test values (1);
    --should work
    insert into test values (1);
    --should work
    insert into test values (2);
    --Should throw error !!!!

    case - II
    truncate table test;
    insert into test values (2);
    --should work
    insert into test values (2);
    --Should work
    insert into test values (1);
    --Should throw error !!!!!!

更新

根据 OP 的两个案例,我认为 BEFORE INSERT TRIGGER 可以完成工作:

测试用例:

SQL> DROP TABLE TEST PURGE;

Table dropped.

SQL>
SQL> CREATE TABLE test
  2    ( col INT
  3    );

Table created.

SQL>
SQL> CREATE OR REPLACE TRIGGER trg BEFORE
  2    INSERT ON TEST FOR EACH ROW DECLARE ID NUMBER;
  3    BEGIN
  4      BEGIN
  5        SELECT DISTINCT col INTO ID FROM TEST;
  6      EXCEPTION
  7      WHEN no_data_found THEN
  8        NULL;
  9      END;
 10      IF :NEW.col <> id THEN
 11        RAISE_APPLICATION_ERROR(-20001, 'Cannot Insert different value in the table');
 12      END IF;
 13    END;
 14  /

Trigger created.

SQL>

NO_DATA_FOUND例外是忽略第一个插入,因为在那之前没有行。

现在,让我们测试 INSERT 语句:

案例 1

SQL> INSERT INTO TEST VALUES (1);

1 row created.

SQL>
SQL> INSERT INTO TEST VALUES (1);

1 row created.

SQL>
SQL> INSERT INTO TEST VALUES (2);
INSERT INTO TEST VALUES (2)
            *
ERROR at line 1:
ORA-20001: Cannot Insert different value in the table
ORA-06512: at "LALIT.TRG", line 10
ORA-04088: error during execution of trigger 'LALIT.TRG'


SQL>

案例 2

SQL> TRUNCATE TABLE TEST;

Table truncated.

SQL>
SQL> INSERT INTO TEST VALUES (2);

1 row created.

SQL>
SQL> INSERT INTO TEST VALUES (2);

1 row created.

SQL>
SQL> INSERT INTO TEST VALUES (1);
INSERT INTO TEST VALUES (1)
            *
ERROR at line 1:
ORA-20001: Cannot Insert different value in the table
ORA-06512: at "LALIT.TRG", line 10
ORA-04088: error during execution of trigger 'LALIT.TRG'


SQL>

如果我没理解错你的要求,你可以使用before insert trigger。检查 table 中存在的值,如果新值与 table 值匹配或 table 没有数据则只允许插入。

这里是link关于触发器 http://docs.oracle.com/cd/B19306_01/appdev.102/b14251/adfns_triggers.htm