oracle 动态sql的用法

本文深入探讨了PL/SQL中动态SQL的使用方法,包括ExecuteImmediate、dbms_sql包以及游标的几种常见操作。通过实例展示了如何灵活运用这些技术进行数据库查询与数据处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在pl/sql中,我们的表名称或者参数是不固定的,经常用到动态sql;

一,几种常用的动态sql的用法

1,Execute Immediate ‘执行的sql’;

2,dbms_sql 包

Declare
  curid Number;
  l_sql Varchar2(1000);
  l_cnt Number(5);
  l_ret Number(5);
  lv_deptno Number(20);


  Type curtype Is Ref Cursor;
  l_curtype curtype;

  Type type_dname Is Table Of dept.Dname%Type  Index By Binary_Integer;
  l_type_dname type_dname;

Begin
  lv_deptno:=20;
   --打开cursor
   curid :=Dbms_Sql.open_cursor;
   --sql语句
   l_sql := 'select dname from dept where Deptno>=:l_deptno';
  --sql解析
  dbms_sql.parse(curid, l_sql, dbms_sql.native);
  --绑定变量
  dbms_sql.bind_variable(curid,':l_deptno',lv_deptno);
  --执行sql
  l_ret     := dbms_sql.execute(curid);
  --转化为ref cursor
  l_curtype := dbms_sql.to_refcursor(curid);

    Fetch l_curtype Bulk Collect Into  l_type_dname;

    For i In 1..l_type_dname.count Loop
      dbms_output.put_line(l_type_dname(i));
      End Loop;
   Close l_curtype;
End;

二,游标的几种用法

1,显示游标

declare
   cursor c_xx is select xx from table_name;

begin
    --打开游标
   open c_xx;
   --取数据
   fetch c_xx into xx

   --close 游标
   close c_xx;

end;

2, ref cursor的用法

Declare
  l_sql Varchar(1000);
  Type cur_typ Is Ref Cursor;
  c cur_typ;
Begin

  For i In (Select t.partition_name
              From dba_segments t
             Where t.segment_name = 'TMP'
               And t.owner = 'SCOTT') Loop
    l_sql := 'select a from tmp Partition(' || i.partition_name || ')';
    Dbms_output.put_line(l_sql);
    Open c For l_sql;
  End Loop;
End;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值