ORA-0001:违反了唯一约束(SYSTEM.BROWSERS_PK)

本文关键字:BROWSERS SYSTEM PK 约束 唯一 ORA-0001 | 更新日期: 2023-09-27 18:21:38

我正在进行一个C#项目,在该项目中,我试图使用以下SQL对Oracle数据库插入一条记录:

String Qry = INSERT INTO browsers (browsers.browser,browsers.engine,browsers.platform,browsers.version,browsers.grade) VALUES ('Alans browser','Gecko','every','1.0','U') RETURNING id INTO :ID

下面是示例代码:http://www.sqlines.com/oracle-to-sql-server-cs-conversion/insert-returning-clause

我的代码如下:

OracleConnection conn = new OracleConnection(...);
OracleCommand cmd = null;
...
cmd = new OracleCommand(Qry, conn);
OracleParameter prm = new OracleParameter();
prm = new OracleParameter(":ID", OracleDbType.Int32, ParameterDirection.ReturnValue);
cmd.Parameters.Add(prm);
cmd.ExecuteNonQuery(); //this line throws error
query.setNewRecordID(cmd.Parameters[":ID"].Value.ToString());
...

当然,浏览器表的id列是用Sequence和Trigger设置的,以便在任何插入时自动递增。我不明白为什么当我没有尝试设置id列时会出现错误。我只是想检索给新记录的id值。

Uddate:以下是创建序列和触发器的SQL命令:

顺序:

CREATE SEQUENCE "SYSTEM"."BROWSERS_SEQ" MINVALUE 1 MAXVALUE 9999999999999999999999999999 INCREMENT BY 1 START WITH 21 CACHE 20 NOORDER NOCYCLE NOPARTITION ;

触发器:

create or replace trigger BROWSERS_TRG  
before insert on "SYSTEM"."BROWSERS" 
for each row 
begin  
   if inserting then 
      if :NEW."ID" is null then 
         select BROWSERS_SEQ.nextval into :NEW."ID" from dual; 
      end if; 
   end if; 
end;

ORA-0001:违反了唯一约束(SYSTEM.BROWSERS_PK)

我认为您的序列有问题(我无法按原样编译)。我去掉了NOPARTITION,它起了作用。

我在我的SCOTT(示例)模式中创建了一个类似的场景,如下所示:

 SCOTT@dev> CREATE TABLE "SCOTT"."EMP2"
  2    (
  3      "EMPNO"    NUMBER(4,0),
  4      "ENAME"    VARCHAR2(10 BYTE),
  5      "JOB"      VARCHAR2(9 BYTE),
  6      "MGR"      NUMBER(4,0),
  7      "HIREDATE" DATE,
  8      "SAL"      NUMBER(7,2),
  9      "COMM"     NUMBER(7,2),
 10      "DEPTNO"   NUMBER(2,0)
 11    )
 12    TABLESPACE "SYSTEM" ;
Table created.
SCOTT@dev> CREATE UNIQUE INDEX "SCOTT"."EMP2_EMPNO" ON "SCOTT"."EMP2"
  2    (
  3      "EMPNO"
  4    )
  5    TABLESPACE "SYSTEM" ;
Index created.
SCOTT@dev> set define off;
SCOTT@dev> ALTER TABLE "SCOTT"."EMP2" ADD PRIMARY KEY ("EMPNO");
Table altered.
SCOTT@dev>  CREATE SEQUENCE EMP2_SEQ MINVALUE 1 MAXVALUE 9999999999999999999999999999 INCREMENT BY 1 START WITH 21 CACHE 20 NOORDER NOCYCLE  ;
Sequence created.
SCOTT@dev> CREATE OR REPLACE TRIGGER EMP2_TRG before
  2    INSERT ON SCOTT.EMP2 FOR EACH row BEGIN IF inserting THEN IF :NEW.EMPNO IS NULL THEN
  3    SELECT EMP2_SEQ.NEXTVAL INTO :NEW.EMPNO FROM dual;
  4  END IF;
  5  END IF;
  6  END;
  7  /
Trigger created.
SCOTT@dev> commit;
Commit complete.
SCOTT@dev> INSERT INTO EMP2
  2  (ENAME)
  3  VALUES
  4  ('FRED')
  5  /
1 row created.
SCOTT@dev> commit;
Commit complete.

因此,序列似乎是罪魁祸首。

您确定序列AND触发器设置正确吗?通常我不使用触发器,而是直接在查询中使用sequencer.nextval。如果您需要在代码的其他部分中使用生成的id,您可以执行"select sequence.nextval from dual"并缓存结果