使用Cursor在SQL中查找重复的行

时间:2015-08-13 14:14:58

标签: sql plsql

我正在使用此循环来更新一行的值。一旦遇到重复的值并打印出重复的行,我该如何退出for循环? 三个键是cust_ref,filter_name和filter_type。

DECLARE

CURSOR c1
IS
  SELECT cust_ref, filter_name, cust_type
  FROM CUSTOMER
  WHERE cust_ref like 'CUST_REF%';

BEGIN

   FOR e in c1

   LOOP

    UPDATE CUSTOMER
    SET cust_ref = REPLACE (cust_ref, 'CUST_REF', 'UNDER_CUST_REF')
    WHERE cust_ref = e.cust_ref
          and filter_name = e.filter_name
          and cust_type = e.cust_type;  

   END LOOP;

END; 

编辑:即使我删除或禁用主键约束,我在执行常规更新语句时也会收到此错误。

SQL Error: ORA-00001: unique constraint (DB.PRIMARYKEY) violated
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. 

1 个答案:

答案 0 :(得分:1)

这应显示您的副本,不要使用光标

SELECT Second.cust_ref, Second.filter_name, Second.cust_type
  FROM CUSTOMER First
  JOIN CUSTOMER Second 
  ON First.cust_ref = REPLACE (Second.cust_ref, 'CUST_REF', 'UNDER_CUST_REF')
  WHERE First.cust_ref like '%CUST_REF%'