开发者

how to insert multiple rows from a source table into a single row in target table using cursor in oracle [duplicate]

开发者 https://www.devze.com 2023-03-09 17:13 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplic开发者_如何转开发ate:
This question already has answers here: Closed 11 years ago.

Possible Duplic开发者_如何转开发ate:

How can multiple rows be concatenated into one in Oracle without creating a stored procedure?

create table pr_info(
   pr_ref varchar2(10),
   pr_text varchar2(3), 
   pr_key varchar2(12)
)

This table contains the data in the following format

pr_ref pr_text  pr_key
a1     abc      qwertyui01 
a1     def      qwertyui02
b1     aaa      zxcvbnmj01
b1     bbb      zxcvbnmj02
b1     ccc      zxcvbnmj03

That is if the pr_text is more than 3 characters long then the record is split and placed in a new record with same pr_ref but different pr_key(in this case the first 8 characters will remain the same but the last two character will signify the sequence of the record)

So now i need to put the data of this table into a new table which has the following sprecification

create table pv_cus(pv_ref vrachar2(10),pv_text varchar2(100))

So basically i need to concatenate the rows belonging to same person from the source table and put it in one row in target table.

pv_ref  pv_text    
a1      abc,def    
b1      aaa,bbb,ccc    


Procedural approach

DECLARE

  type pv_ref_t is TABLE of pv_cus.pv_ref%type;
  type pv_text_t is TABLE of pv_cus.pv_text%type;
  v_pv_ref_tab pv_ref_t;
  v_pv_text_tab pv_text_t;
  v_last_pr_ref  pr_info.pr_ref%type;
BEGIN
  v_pv_ref_tab := pv_ref_t();
  v_pv_text_tab := pv_text_t();

  FOR rec in (SELECT pr_ref, pr_text FROM pr_info order by  pr_ref, pr_key)
  LOOP
    IF v_last_pr_ref IS NULL
    OR v_last_pr_ref != rec.pr_ref
    THEN
      v_last_pr_ref := rec.pr_ref;
      v_pv_ref_tab.extend(1);
      v_pv_text_tab.extend(1);
      v_pv_ref_tab(v_pv_ref_tab.last) := rec.pr_ref;
      v_pv_text_tab(v_pv_text_tab.last) := rec.pr_text;
    ELSE
      -- tbd: check length of v_pv_text_tab(v_pv_text_tab.last)
      v_pv_text_tab(v_pv_text_tab.last) := v_pv_text_tab(v_pv_text_tab.last) || ',' || rec.pr_text;
    END IF;

  END LOOP;

  FORALL  i in 1..v_pv_ref_tab.last
    INSERT INTO pv_cus (pv_ref, pv_text) VALUES(v_pv_ref_tab(i), v_pv_text_tab(i))
  ;
END;
/
0

精彩评论

暂无评论...
验证码 换一张
取 消