Oracle PLSQL中使用游标的动态列名

时间:2014-03-06 12:49:16

标签: oracle plsql

我需要在循环中动态生成列名,并使用PLSQL访问oracle表中的列。我该怎么做?

DECLARE
 varValue VARCHAR(20);
 CURSOR c IS
  SELECT * FROM TEST1;
 BEGIN
     FOR i IN c LOOP
       FOR j IN 1..5
       LOOP
        EXECUTE IMMEDIATE 'SELECT ''NAME1'||to_Char(j)||''' from dual' INTO varValue;
         dbms_output.put_line(j);
         dbms_output.put_line(i.varValue);
       END LOOP;
     END LOOP;
 END;

实际问题是,我需要通过游标(c)给出每行(i)的单元格值,例如i.name11,i.name12 .... i.name1100。在每个单元中部署的逻辑是相同的。所以我需要这里使用的列名,即动态生成name11。这已经完成并存储到变量varValue。现在我如何访问单元格i.varValue,以便在循环中生成var值。

错误如下:

ORA-06550: line 14, column 34:
PLS-00302: component 'VARVALUE' must be declared
ORA-06550: line 14, column 11:
PL/SQL: Statement ignored

1 个答案:

答案 0 :(得分:0)

DECLARE
 varValue VARCHAR(20);
 CURSOR c IS
  SELECT * FROM TEST1;
 BEGIN
     FOR i IN c LOOP
       FOR j IN 1..5
       LOOP
        EXECUTE IMMEDIATE 'SELECT ''NAME1'||to_Char(j)||''' from dual' INTO varValue;
         dbms_output.put_line(j);
         dbms_output.put_line('NAME1'||to_Char(j)||' : '||varValue);
       END LOOP;
     END LOOP;
 END;