2016-10-15 39 views
0

我想在我的过程中动态执行sql语句。据我所知,绑定是根据用法的顺序完成的。PLSQL动态SQL按名称绑定变量

有没有一种方式,我可以这样说

:a --> par_a_ 
+0

'我想执行一个SQL语句dynamically'什么样的SQL语句? –

回答

2

execute immediate 'plsql code'execute immediate 'sql'之间的differnce,在动态PL/SQL oracle会使用真实bindes,你可以以正确的顺序指定一次,它会取代所有的绑定,如果有repeted 。与SQL你应该spesify所有绑定,而不是重复它。

declare 
    l_sql varchar2(4000) := 'select :a from dual union all select :a from dual'; 
    l_pl_sql varchar2(4000) := 'begin dbms_output.put_line(:a); dbms_output.put_line(:a); end;'; 
    type t_tab_str is table of varchar2(4000); 
    l_res t_tab_str ; 
begin 
    execute immediate l_sql bulk collect into l_res using '1','2'; 
    for i in 1.. l_res.last loop 
    dbms_output.put_line(l_res(i)); 
    end loop; 
    execute immediate l_pl_sql using '1'; 
end; 

您可以使用DBMS_SQL和它的功能绑定

declare 
    l_sql varchar2(4000) := 'select :a from dual union all select :a from dual'; 
    type t_tab_str is table of varchar2(4000); 
    l_res t_tab_str ; 
    l_sql_id number; 
    l_ret number; 
    type curtype is ref cursor; 
    l_cursor curtype ; 
begin 
    dbms_sql.parse(l_sql_id ,l_sql,dbms_sql.native); 
    dbms_sql.bind_variable(l_sql_id,'a','1'); 
    l_ret := dbms_sql.execute(l_sql_id); 
    l_cursor := dbms_sql.to_refcursor(l_sql_id); 
    fetch l_cursor bulk collect into l_res; 
    for i in 1.. l_res.last loop 
    dbms_output.put_line(l_res(i)); 
    end loop; 
end; 
1

在我看来,你是什么后USING关键字。

下面是来自oracle文档的示例。

DECLARE 
    plsql_block VARCHAR2(500); 
    new_deptid NUMBER(4); 
    new_dname VARCHAR2(30) := 'Advertising'; 
    new_mgrid NUMBER(6) := 200; 
    new_locid NUMBER(4) := 1700; 
BEGIN 
-- Dynamic PL/SQL block invokes subprogram: 
    plsql_block := 'BEGIN create_dept(:a, :b, :c, :d); END;'; 

/* Specify bind arguments in USING clause. 
    Specify mode for first parameter. 
    Modes of other parameters are correct by default. */ 
    EXECUTE IMMEDIATE plsql_block 
    USING IN OUT new_deptid, new_dname, new_mgrid, new_locid; 
END; 
/

https://docs.oracle.com/cd/B28359_01/appdev.111/b28370/dynamic.htm