我有一个包含两个字符的表:product(varchar)和用法(varchar)。我需要以“product; usage; product; usage ...”格式将表循环到一个变量。如何才能做到这一点?以下循环不起作用:
FOR product IN (SELECT product FROM licence_check) LOOP
product_usage := (licence_check.product || ';' || licence_check.usage);
END LOOP;
答案 0 :(得分:5)
它必须是一个循环吗?对于那么多的值,LISTAGG
可以完成这项工作:
SQL> select listagg(dname||';'||loc, ';') within group (order by deptno) result
2 from dept;
RESULT
--------------------------------------------------------------------------------
ACCOUNTING;NEW YORK;RESEARCH;DALLAS;SALES;CHICAGO;OPERATIONS;BOSTON
SQL>
如果必须是LOOP,我会说你错过了与PRODUCT_USAGE本身的连接。看看:
SQL> declare
2 l_result varchar2(100);
3 begin
4 for cur_r in (select dname, loc from dept) loop
5 l_result := l_result || cur_r.dname ||';'||cur_r.loc ||';';
-----------
This is what you miss
6 end loop;
7 dbms_output.put_line(rtrim(l_result, ';'));
8 end;
9 /
ACCOUNTING;NEW YORK;RESEARCH;DALLAS;SALES;CHICAGO;OPERATIONS;BOSTON
PL/SQL procedure successfully completed.
SQL>