Cursor For Loop with dynamic SQL-Statement(带有动态 SQL 语句的游标 For 循环)
问题描述
有没有办法用动态 SQL 语句执行 Cursor For 循环?
Is there a way to perform a Cursor For Loop with an dynamic SQL-statement?
如果我不想声明记录,我可以这样做(仅当我声明了游标..):
If I don't want to declare a record I can do something like this (only if I declared the cursor..):
For I in cuSelect Loop
dbms_output.put_line(I.NAME);
End Loop;
我可以为动态 SQL 语句打开一个游标:
And I can open a cursor for a dynamic SQL-statement:
Open cuSelect For 'Select * From TAB_X';
Fetch ceSelect Into recSelect;
Close cuSelect;
但要做到这一点,我必须先声明 Record.
But to do that I have to first declare the Record.
现在我的问题是我必须为一个非常大和复杂的动态 SQL 语句打开 Cursor.记录的结构未知.有没有办法打开一个变量游标并用未声明"的记录遍历它?
Now my problem is that I have to open the Cursor for a very big and complicated dynamic SQL-statement. The structure of the record is unknown. Is there a way to open a variable cursor and iterate through it with an "undeclared" record?
推荐答案
我认为你可以用 DBMS_SQL 包做你想做的事.
I think you can do what you want with DBMS_SQL package.
您还可以检查这些:
- 使用动态 SQL
- COLUMN_VALUE 程序
例如:
declare
TYPE curtype IS REF CURSOR;
src_cur curtype;
curid NUMBER;
namevar VARCHAR2(50);
numvar NUMBER;
datevar DATE;
desctab DBMS_SQL.DESC_TAB;
colcnt NUMBER;
dsql varchar2(1000) := 'select card_no from card_table where rownum = 1';
begin
OPEN src_cur FOR dsql;
-- Switch from native dynamic SQL to DBMS_SQL package.
curid := DBMS_SQL.TO_CURSOR_NUMBER(src_cur);
DBMS_SQL.DESCRIBE_COLUMNS(curid, colcnt, desctab);
-- Define columns.
FOR i IN 1 .. colcnt LOOP
IF desctab(i).col_type = 2 THEN
DBMS_SQL.DEFINE_COLUMN(curid, i, numvar);
ELSIF desctab(i).col_type = 12 THEN
DBMS_SQL.DEFINE_COLUMN(curid, i, datevar);
ELSE
DBMS_SQL.DEFINE_COLUMN(curid, i, namevar, 50);
END IF;
END LOOP;
-- Fetch rows with DBMS_SQL package.
WHILE DBMS_SQL.FETCH_ROWS(curid) > 0 LOOP
FOR i IN 1 .. colcnt LOOP
IF (desctab(i).col_type = 1) THEN
DBMS_SQL.COLUMN_VALUE(curid, i, namevar);
dbms_output.put_line(namevar);
ELSIF (desctab(i).col_type = 2) THEN
DBMS_SQL.COLUMN_VALUE(curid, i, numvar);
dbms_output.put_line(numvar);
ELSIF (desctab(i).col_type = 12) THEN
DBMS_SQL.COLUMN_VALUE(curid, i, datevar);
dbms_output.put_line(datevar);
END IF;
END LOOP;
END LOOP;
DBMS_SQL.CLOSE_CURSOR(curid);
end;
这篇关于带有动态 SQL 语句的游标 For 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:带有动态 SQL 语句的游标 For 循环
基础教程推荐
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- SQL Server 2016更改对象所有者 2022-01-01
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- Sql Server 字符串到日期的转换 2021-01-01
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01