简体   繁体   中英

I want to covert rows from one table to columns to another table using Procedures(Pl/sql)

table A:

col1
_______________________
jack 
1200
20
peter
2000
10
robert 
300
30

to

table B :

name   sal   deptno
-----------------------
jack 1200 20
peter 2000 10
robert 300 30

here I want this by using procedure parameter. can you please help I tried with it but it is giving errors.

create procedure GetDatafromtable_A(V_1 in varchar2)
as
CURSOR rwdatacursor IS select Raw_Data  from table_a where rowid<=3)
T_record rwdatacursor%rowtype;
begin
open rwdatacursor;
loop
fetech rwdatacursor into T_record;
exit when rwdatacursor%NOTFUND;
insert into temp_process;
end loop
close rwdatacursor;
end;

This is the codew I have tried but showing lot of errors

One way to do this is:

PROCEDURE CONVERT_TABLES IS
  CURSOR DATA_CURSOR IS
    SELECT COL1
      FROM TABLE_A;

  row1 DATA_CURSOR%ROWTYPE;
  row2 DATA_CURSOR%ROWTYPE;
  row3 DATA_CURSOR%ROWTYPE;
BEGIN
  OPEN DATA_CURSOR;

  LOOP
    FETCH DATA_CURSOR INTO row1;
    EXIT WHEN DATA_CURSOR%NOTFOUND;

    FETCH DATA_CURSOR INTO row2;
    EXIT WHEN DATA_CURSOR%NOTFOUND;

    FETCH DATA_CURSOR INTO row3;
    EXIT WHEN DATA_CURSOR%NOTFOUND;

    INSERT INTO TABLE_B (NAME, SAL, DEPTNO)
      VALUES (row1.COL1, row2.COL1, row3.COL1);
  END LOOP;

  CLOSE DATA_CURSOR;
END CONVERT_TABLES;

Share and enjoy.

Try this. Assuming that each consecutive three rows are name sal and deptno . May be some complicated logic but try it if it helps you.

CREATE TABLE #temp(slNo INT IDENTITY(1,1),col1 VARCHAR(50))
INSERT INTO #temp 
SELECT col1 FROM table_A

INSERT INTO table_B(name  , sal ,  deptno)
SELECT name,sal,depno
FROM 
  (  SELECT col1 AS name, ROW_NUMBER() OVER (ORDER BY col1) AS RowNum 
     FROM #temp WHERE slNo % 3 =1) AS T1
  FULL OUTER JOIN
    (SELECT col1 AS sal, ROW_NUMBER() OVER (ORDER BY col1) AS RowNum 
     FROM #temp WHERE slNo%3=2) AS T2
  ON T2.RowNum = T1.RowNum
  FULL OUTER JOIN 
      (SELECT col1 AS depno, ROW_NUMBER() OVER (ORDER BY col1) AS RowNum 
       FROM #temp WHERE slNo%3=0) AS T3
  ON T3.RowNum = T2.RowNum
  )

Result

结果

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM