从 sqlplus 显示 pl/sql 内的动态 EXECUTE 输出
如何从Oracle sqlplus
获取PL/SQL中EXECUTE
的动态选择结果?
我正在编写一个简单的 sqlplus 脚本来收集给定表的所有 NUMBER
列的总和:
SET SERVEROUTPUT ON
DECLARE
CURSOR column_cur IS
SELECT column_name FROM ALL_TAB_COLS
WHERE owner = '&scheme_name' AND table_name = '&table_name'
AND data_type = 'NUMBER';
sql_query VARCHAR2(32767);
BEGIN
sql_query := 'select ';
FOR column_rec IN column_cur LOOP
sql_query := sql_query || 'SUM(' || column_rec.column_name ||
') "SUM(' || column_rec.column_name || ')", ';
END LOOP;
sql_query := substr(sql_query, 0, length(sql_query)-2) || -- remove trailing ', '
' from &scheme_name' || '.&table_name';
EXECUTE IMMEDIATE sql_query;
END;
/
动态生成的 SQL 语句在执行时会给出类似以下内容:
SUM(X) | SUM(Y) | SUM(Z) |
--------------------------
111 | 222 | 333 |
但是,即使使用 SET SERVEROUTPUT ON
,运行 sqlplus 脚本仅给出:
PL/SQL procedure successfully completed.
How to get the dynamic select results of EXECUTE
within PL/SQL from Oracle sqlplus
?
I'm writing a simple sqlplus script to collect the sum of all NUMBER
columns of a given table:
SET SERVEROUTPUT ON
DECLARE
CURSOR column_cur IS
SELECT column_name FROM ALL_TAB_COLS
WHERE owner = '&scheme_name' AND table_name = '&table_name'
AND data_type = 'NUMBER';
sql_query VARCHAR2(32767);
BEGIN
sql_query := 'select ';
FOR column_rec IN column_cur LOOP
sql_query := sql_query || 'SUM(' || column_rec.column_name ||
') "SUM(' || column_rec.column_name || ')", ';
END LOOP;
sql_query := substr(sql_query, 0, length(sql_query)-2) || -- remove trailing ', '
' from &scheme_name' || '.&table_name';
EXECUTE IMMEDIATE sql_query;
END;
/
The dynamically generated SQL statement, when executed, gives something like:
SUM(X) | SUM(Y) | SUM(Z) |
--------------------------
111 | 222 | 333 |
However, even with SET SERVEROUTPUT ON
, running the sqlplus script gives only:
PL/SQL procedure successfully completed.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要从 SELECT 中检索结果才能显示它。您可以使用 Syntax
EXECUTE IMMEDIATE sql_query INTO var1, var2.. varn
。但是,在您的情况下,列数在编译时未知。有多种方法可以处理这个问题:
我将演示 1:
you will need to retrieve the result from your SELECT in order to display it. You would use the synthax
EXECUTE IMMEDIATE sql_query INTO var1, var2.. varn
. However in your case the number of columns is unknown at compile time.There are a number of ways you could deal with this:
I will demo 1: