嵌套替换以进行更新

时间:2018-09-12 11:06:08

标签: sql oracle plsql

我有带光标的包装,是否想替换列中的某些字符?选择有效,但我需要更新,谢谢。 这是我的代码:

DECLARE
    CURSOR get_data
    IS
        SELECT e.column1,
               e.column2,
               d.column3,
               d.column4
          FROM table1 e, table2 d
         WHERE e.column1 = d.column3;
BEGIN
    FOR i IN get_data
    LOOP
        UPDATE table1
           SET column1 = REPLACE (REPLACE (column1, 'OPRS', 'V'), 'ABV', 'T')
         WHERE column1 = i.column1
           AND column1 LIKE '2027044%';

        UPDATE table2
           SET column3 = REPLACE (REPLACE (column3, 'OPRS', 'V'), 'ABV', 'T');
    END LOOP;
END;

错误是:

ORA-00001: unique constraint (DB_KSS_ONLINE.NETOPERIDX) violated ORA-06512: at line 10
00001. 00000 - "unique constraint (%s.%s) violated"
*Cause: An UPDATE or INSERT statement attempted to insert a duplicate key.
For Trusted Oracle configured in DBMS MAC mode, you may see this message if a duplicate entry exists at a different level.
*Action: Either remove the unique restriction or do not insert the key.

2 个答案:

答案 0 :(得分:0)

代码为:

update table1  
   set column1 = REPLACE(REPLACE(column1, 'OPRS', 'V'), 'ABV', 'T')  ;

我认为您只是想念=

我建议添加:

where column1 like '%OPRS%' or column1 like '%ABV%'

这将更新逻辑仅限于匹配的行。

答案 1 :(得分:0)

从您的光标查询中,我们可以看到table1.column1table2.column3是标识符。这些也是您在UPDATE语句中处理的列。因此,过程逻辑中存在空白,这意味着SET子句在唯一列中生成重复值。看来您的数据状态与您认为的状态不同。

要解决此问题,您需要对数据进行一些调查。

  1. 您编辑的代码中DB_KSS_ONLINEtable1还是table2的真实名称?这会告诉您需要调查哪些数据。
  2. 运行SELECT语句,该语句复制更新后的值。这告诉您需要设置哪些其他规则(过滤器)。

类似这样的东西:

SELECT e.column1
       , case when e.column1 like '2027044%' then
              REPLACE(REPLACE(column1, 'OPRS', 'V'), 'ABV', 'T')   
              else null 
         end as updated_col1
       , d.column3
       , REPLACE(REPLACE(column3, 'OPRS', 'V'), 'ABV', 'T') as updated_col3
       , e.column2
       , d.column4
  FROM table1 e, table2 d
  WHERE  e.column1 = d.column3
  order by 4 nulls last, 2 nulls last ;