日期:2014-05-16  浏览次数:20432 次

使用Oracle的DBMS_SQL包执行动态SQL语句

?

在某些场合下,存储过程或触发器里的SQL语句需要动态生成。Oracle的DBMS_SQL包可以用来执行动态SQL语句。本文通过一个简单的例子来展示如何利用DBMS_SQL包执行动态SQL语句:

?

DECLARE
v_cursor NUMBER;
v_stat NUMBER;
v_row NUMBER;
v_id NUMBER;
v_no VARCHAR(100);
v_date DATE;
v_sql VARCHAR(200);
s_id NUMBER;
s_date DATE;
BEGIN
s_id := 3000;
s_date := SYSDATE;
v_sql := 'SELECT id,qan_no,sample_date FROM "tblno" WHERE id > :sid and sample_date < :sdate ';
v_cursor := dbms_sql.open_cursor ;--打开游标;
dbms_sql.parse (v_cursor, v_sql, dbms_sql.native);--解析动态SQL语句;
dbms_sql.bind_variable (v_cursor, ':sid', s_id); --绑定输入参数;
dbms_sql.bind_variable (v_cursor, ':sdate', s_date);

dbms_sql.define_column (v_cursor, 1, v_id);
--定义列
dbms_sql.define_column (v_cursor, 2, v_no, 100);
dbms_sql.define_column (v_cursor, 3, v_date);
v_stat := dbms_sql.execute (v_cursor);
--执行动态SQL语句。
LOOP
EXIT WHEN dbms_sql.fetch_rows (v_cursor)<=0;
--fetch_rows在结果集中移动游标,如果未抵达末尾,返回1。
dbms_sql.column_value (v_cursor, 1, v_id);
--将当前行的查询结果写入上面定义的列中。
dbms_sql.column_value (v_cursor, 2, v_no);
dbms_sql.column_value (v_cursor, 3, v_date);
dbms_output.put_line(v_id || ';' || v_no || ';' || v_date);
END LOOP;
dbms_sql.close_cursor (v_cursor);
--关闭游标。
END;

?

结果:

?

3095;S051013XW00010;15-10月-05
3112;A051013XW00027;10-10月-05
3113;A051013XW00028;13-10月-05
3116;S051013XW00031;13-10月-05

<!--StartFragment -->

?

?

附:DBMS_SQL的文档(来源:http://www.psoug.org )

{ graphic1= new Image(); graphic1.src = "../source/home1.jpg"; graphic1on = new Image(); graphic1on.src = "../source/home2.jpg"; graphic2= new Image(); graphic2.src = "../source/education1.jpg"; graphic2on = new Image(); graphic2on.src = "../source/education2.jpg"; } function imageChg(imageID2,imageName2) { { document.images[imageID2].src = eval(imageName2 + ".src"); } }

Oracle DBMS_SQL

Version 10.2

General
Note: DMBS_SQL is the traditional form of dynamic SQL in Oracle.

For most purposes native dynamic sql (NDS) will suffice but there are some things the DBMS_SQL package does that can not be done any other way. This page emphasizes those areas where there is no substitute.
Purpose
Source {ORACLE_HOME}/rdb