2016-10-15 66 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