【问题标题】:Oracle Unique Key - get PK or RowIDOracle 唯一密钥 - 获取 PK 或 RowID
【发布时间】:2020-01-02 22:10:17
【问题描述】:

是否可以捕获触发复制异常的主键或记录rowID?

table1 有 PK: col1 和 Unique1: col2

例如

begin
  insert into table1(col1, col2, col3)
  values (1, 2, 3);
exception
  when dup_val_on_index then
    --- here, can you somehow indicate either PK or ROWID of the record that generated the exception of uniqueness?
  e.g.
  update table1 set 
    col3 = 100
  where rowid = "GETROWID" or col1 = "GETPK";
end;

【问题讨论】:

  • 我不这么认为。
  • 您的表上有多少个索引?哪一列?
  • 没关系,就是检测哪条记录已经存在了……我想没有这样的机制,但这就是我想问的……但事实是,如果有很多唯一索引,可能有很多处于危险之中,那么它不会是一个 ROWID 而是很多......
  • 这很重要。我问的原因是您可以查询您的表以查找导致异常的匹配记录,然后从那里处理它。我认为这将是你唯一的选择。
  • 那个我可以问数据库很清楚,但我认为有办法“自动”获取

标签: oracle primary-key unique-key


【解决方案1】:

在“普通”代码中,您不使用常量来插入值;您通常会将值放在变量中,因此您的代码看起来更像:

DECLARE
  strVar1    TABLE1%TYPE;
  nVar2      NUMBER;
  nVar3      NUMBER;
begin
  SELECT s1, n2, n3
    INTO strVar1, nVar2, nVar3
    FROM SOME_TABLE;

  insert into table1(col1, col2, col3)
    values (strVar1, nVar2, nVar3);
exception
  when dup_val_on_index then
    update table1
      set col3 = 100
      where col1 = strVar1;
end;

但更好的办法是首先通过使用 MERGE 语句来避免异常:

MERGE INTO TABLE1 t1
  USING (SELECT S1, N2, N3
           FROM SOME_TABLE) s
    ON (t1.COL1 = s.S1)
  WHEN MATCHED THEN
    UPDATE SET COL3 = 100
  WHEN NOT MATCHED THEN
    INSERT (COL1, COL2, COl3)
    VALUES (s.S1, s.N2, s.N3);

【讨论】:

    【解决方案2】:

    LOG ERRORS INTO 在这里可以提供帮助。在使用这个子句之前你必须准备一个错误表:

    begin
      dbms_errlog.create_error_log('table1');
    end;
    

    这将创建 err$_table1 表。现在使用附加功能运行插入

    insert into table1(col1, col2, col3) values (1, 2, 3)
    log errors into err$_table1 ('some_tag_to_look_for') reject limit unlimited;
    

    使用 err$_table1 查询 select * from err$_table1;

    不会为您提供 rowid(它仅用于更新和删除),但您将获得导致错误和违反索引的确切列值。

    如果这还不够,你可以在这里找到索引列

    select * from all_ind_columns where owner='OWNER_NAME_from_error_table' and index_name = 'Name_from_err_table';
    

    因此,您将知道目标表中的哪些列已经具有您尝试插入的值 --> 这就是您将如何找到 rowid 或您需要的任何内容

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-15
      • 1970-01-01
      • 2010-09-08
      • 2023-04-04
      • 2015-08-04
      • 2017-11-15
      • 1970-01-01
      相关资源
      最近更新 更多