Oracle存储过程使用动态SQL

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

1:DDL和DML

/*** DDL ***/  
begin   
    EXECUTE IMMEDIATE 'drop table temp_1';   
EXECUTE IMMEDIATE 'create table temp_1(name varchar2(8))';   
end;  
/*** DML ***/  
declare   
 v_1 varchar2(8);   
 v_2 varchar2(10);   
 str varchar2(50);   
begin   
  v_1:='macower’;   
 v_2:='深圳;   
str := 'INSERT INTO test (name ,address) VALUES (:1, :2)';   
    EXECUTE IMMEDIATE str USING v_1, v_2;   
   commit;   
end;  

2. 返回单条结果(核心是rownum=1)

 

declare       
	str varchar2(500);       
	c_1 varchar2(10);       
	r_1 test%rowtype;   
begin       
	c_1:='测试人员';       
	str:='select * from test where name=:c WHERE ROWNUM=1';       
execute immediate str into r_1 using c_1;       
DBMS_OUTPUT.PUT_LINE(R_1.NAME||R_1.ADDRESS);   
end ; 



3:返回结果集(游标)

 

CREATE OR REPLACE package pkg_test as   

    /* 定义ref cursor类型   

    不加return类型,为弱类型,允许动态sql查询,   

    否则为强类型,无法使用动态sql查询;   

    */   

    type myrctype is ref cursor;  

     --函数申明   

    function get(intID number) return myrctype;   

end pkg_test;   

/  


 

CREATE OR REPLACE package body pkg_test as   

--函数体   

    function get(intID number) return myrctype is   
       rc myrctype; --定义ref cursor变量   
        sqlstr varchar2(500);   
    begin   
        if intID=0 then   
            --静态测试,直接用select语句直接返回结果   
          open rc for select id,name,sex,address,postcode,birthday from student;
       else   
            --动态sql赋值,用:w_id来申明该变量从外部获得   
            sqlstr := 'select id,name,sex,address,postcode,birthday from student where id=:w_id';   
            --动态测试,用sqlstr字符串返回结果,用using关键词传递参数   
            open rc for sqlstr using intid;   

        end if;  
         return rc;   
   end get;  
 end pkg_test;   



 

 

你可能感兴趣的:(Oracle存储过程使用动态SQL)