在光标内循环插入记录

问题描述:

我是初学者,我有这个问题。所以我有一个表:在光标内循环插入记录

config_items:

id | item_key   | item_alias | 
---|---------------------|------------| 
5 | folder1.Move.hasFile| hasFile | 
4 | folder1.Move  | Move  |  
3 | folder2.Move  | Move  | 
2 | folder3.Move  | Move  | 
1 | folder4.Download | Download | 

我要带它有.Move在其item_key记录。获得这些记录后,我想在每个记录上添加.hasFile,并将它们作为新记录插入到表中。但是,如果该config_key已经存在(例如folder1.Move.hasFile),不应该添加在表上。我已经做了以下,但它给我主键违规错误的ID。有人能解释我在哪里做错了吗?

CREATE OR REPLACE PROCEDURE insert_hasFile(v_key IN config_items.item_key%TYPE) 
AS 
BEGIN 
    insert into config_items 
      (id, 
      item_key, 
      item_alias) 
      (select 
       (select max(id) from config_items)+1, 
       v_key, 
       'hasFile' 
      from 
       config_items 
      where 
       not exists(select * from config_items where v_key =item_key) 
      ); 
END; 
/

DECLARE 
CURSOR item_records_curr 
IS 
SELECT * from config_items 
where item_key LIKE '%.Move'; 

v_item_key config_items.item_key%TYPE; 
v_all_info item_records_curr%ROWTYPE; 

BEGIN 
    OPEN item_records_curr; 

    LOOP 
     FETCH item_records_curr into v_all_info;  
     v_item_key := v_all_info.item_key || '.hasFile'; 
     insert_hasFile(v_item_key); 
     EXIT WHEN item_records_curr%NOTFOUND; 
    END LOOP; 

    CLOSE item_records_curr; 
END; 
+0

没有了PK包含哪些列?只有身份证或其他东西? – Aleksej

+0

使用'max(id)'来计算主键的唯一值是个不错的主意。你应该使用序列 - 这是更好的方法。 – AlexSmet

+0

@Aleksej id是PK。 item_key必须是唯一的。 – Rthp

假设你至少有甲骨文12C你可以只作ID在你的表声明的标识字段,例如所产生默认情况下,NULL身份

这样,你不必ID NUMBER担心试图在SP中计算,并且可以让系统为此生成密钥。

如此处所述。 http://docs.oracle.com/database/121/DRDAA/migr_tools_feat.htm#DRDAA109

在你的程序中insert_hasFile你是从config_items表,将选择与ID列值相同的多个记录读取记录。

试图通过使用DUAL如下面的步骤插入单个记录..

`CREATE OR REPLACE PROCEDURE insert_hasFile(v_key IN config_items.item_key%TYPE) 
AS 
BEGIN 
    insert into config_items 
      (id, 
      item_key, 
      item_alias) 
      (select 
       (select max(id) from config_items)+1, 
        v_key, 
       'hasFile' 
      from 
       dual 
      where 
       not exists(select * from config_items where v_key =item_key) 
      ) ; 
END; 
/`