如何迭代oraclepl/sql中的列名?

ykejflvf  于 2021-07-29  发布在  Java
关注(0)|答案(2)|浏览(323)

我尝试遍历sql的列名以应用一些动态查询。但是,我在迭代这些列名时遇到了一个问题。
我总是有一个错误,通常是pl/sql编译错误。
代码如下:
sql代码:

DECLARE
 CURSOR c IS
  SELECT COLUMN_NAME FROM ALL_COL_COMMENTS WHERE table_name='my_table_name';
 BEGIN
     FOR current_field IN c LOOP
         dbms_output.put_line(current_field);
         ...Dynamic SELECT QUERY
         new_string = new_string || ',' || current_field;
         dbms_output.put_line(new_string);
     END LOOP;
 END;

最后一个目标是统计每次在sql查询中添加新字段并保存其结果时的观察次数。
伪代码:

current string = ''
result = array(len(all_field))
for current_field in all_field:
   result[idx] = SQL_QUERY(current_string)
   current_string = current_string + ',' + current_field
rur96b6h

rur96b6h1#

尝试:

set echo on
set serveroutput on
DECLARE
 new_string varchar2(250);
 CURSOR c IS
  SELECT COLUMN_NAME FROM ALL_COL_COMMENTS WHERE table_name='mytablename';
BEGIN
  FOR current_field IN c LOOP
      dbms_output.put_line(current_field.column_name);
      new_string := new_string || ',' || current_field.column_name;
      dbms_output.put_line(new_string);
 END LOOP;
END;
/
yqyhoc1h

yqyhoc1h2#

这不是对您问题的回答,但我通常使用 LISTAGG :

CREATE TABLE t (a NUMBER, b NUMBER, c NUMBER);

SELECT LISTAGG(column_name, ',') WITHIN GROUP (ORDER BY column_id) AS cols
  FROM user_tab_columns
 WHERE table_name = 'T';

COLS
A,B,C

相关问题