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

时间:2014-09-12 18:01:12

标签: c# sql oracle

我正在开发一个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;

2 个答案:

答案 0 :(得分:1)

我认为您的序列存在问题(我无法按原样编译)。我从中取出了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.

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

答案 1 :(得分:0)

您确定顺序AND触发器设置正确吗?通常我不会使用触发器,而只是将sequencer.nextval直接用于​​查询。如果您需要在代码的其他部分使用生成的ID,您可以执行从双重'中选择sequence.nextval。并缓存结果