当前位置: 代码迷 >> SQL >> ORACLE 动态实施SQL语句
  详细解决方案

ORACLE 动态实施SQL语句

热度:8   发布时间:2016-05-05 12:32:39.0
ORACLE 动态执行SQL语句

转自:http://zhaisx.iteye.com/blog/856472

ORACLE 动态执行SQL语句

博客分类:
    ?
  • Oracle
SQLOracleCC++C#?

Oracle 动态SQL
Oracle 动态SQL有两种写法:用 DBMS_SQL 或 execute immediate,建议使用后者。试验步骤如下:


1. DDL 和 DML

Sql代码??收藏代码
  1. /***?DDL?***/??
  2. begin??
  3. ????EXECUTE?IMMEDIATE?'drop?table?temp_1';??
  4. ????EXECUTE?IMMEDIATE?'create?table?temp_1(name?varchar2(8))';??
  5. end;??
  6. ??
  7. /***?DML?***/??
  8. declare??
  9. ????v_1?varchar2(8);??
  10. ????v_2?varchar2(10);??
  11. ????str?varchar2(50);??
  12. begin??
  13. ????v_1:='测试人员';??
  14. ????v_2:='北京';??
  15. ????str?:=?'INSERT?INTO?test?(name?,address)?VALUES?(:1,?:2)';??
  16. ????EXECUTE?IMMEDIATE?str?USING?v_1,?v_2;??
  17. ????commit;??
  18. end;??
?



2. 返回单条结果

Sql代码??收藏代码
  1. declare??
  2. ????str?varchar2(500);??
  3. ????c_1?varchar2(10);??
  4. ????r_1?test%rowtype;??
  5. begin??
  6. ????c_1:='测试人员';??
  7. ????str:='select?*?from?test?where?name=:c?WHERE?ROWNUM=1';??
  8. ????execute?immediate?str?into?r_1?using?c_1;??
  9. ????DBMS_OUTPUT.PUT_LINE(R_1.NAME||R_1.ADDRESS);??
  10. end?;??
?



3. 返回结果集

?

Sql代码??收藏代码
  1. CREATE?OR?REPLACE?package?pkg_test?as??
  2. ????/*?定义ref?cursor类型??
  3. ????不加return类型,为弱类型,允许动态sql查询,??
  4. ????否则为强类型,无法使用动态sql查询;??
  5. ????*/??
  6. ????type?myrctype?is?ref?cursor;??
  7. ??
  8. ????--函数申明??
  9. ????function?get(intID?number)?return?myrctype;??
  10. end?pkg_test;??
  11. /??
  12. ??
  13. CREATE?OR?REPLACE?package?body?pkg_test?as??
  14. --函数体??
  15. ????function?get(intID?number)?return?myrctype?is??
  16. ????????rc?myrctype;?--定义ref?cursor变量??
  17. ????????sqlstr?varchar2(500);??
  18. ????begin??
  19. ????????if?intID=0?then??
  20. ????????????--静态测试,直接用select语句直接返回结果??
  21. ????????????open?rc?for?select?id,name,sex,address,postcode,birthday?from??
  22. student;??
  23. ????????else??
  24. ????????????--动态sql赋值,用:w_id来申明该变量从外部获得??
  25. ????????????sqlstr?:=?'select?id,name,sex,address,postcode,birthday?from?student??
  26. where?id=:w_id';??
  27. ????????????--动态测试,用sqlstr字符串返回结果,用using关键词传递参数??
  28. ????????????open?rc?for?sqlstr?using?intid;??
  29. ????????end?if;??
  30. ??
  31. ????????return?rc;??
  32. ????end?get;??
  33. ??
  34. end?pkg_test;??
  35. / ?
  相关解决方案