我想使用Procedures(Pl / sql)将行从一个表转换为列到另一个表

时间:2013-07-23 09:41:22

标签: sql oracle plsql procedures

table A:

col1
_______________________
jack 
1200
20
peter
2000
10
robert 
300
30

table B :

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

这里我想通过使用procedure参数来实现这一点。你可以帮我试试但是它会给出错误。

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;

这是我尝试的代码,但显示了很多错误

2 个答案:

答案 0 :(得分:1)

一种方法是:

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;

分享并享受。

答案 1 :(得分:0)

试试这个。假设每个consecutive three rows are name sal and deptno。可能是一些复杂的逻辑,但如果它对你有帮助就试试吧。

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