Oracle

在 Oracle 中使用“動態 SQL”和“綁定變數”時如何在儲存過程的輸出部分顯示準確的查詢

  • July 25, 2020

我有一個程序,如下所示。在這個過程中,我有一個變數,我正在使用dynamic query它來消除注入風險並提高性能:qry``Bind variable

create or replace procedure first_test(i_tx varchar2, o_count out number) is

qry varchar2(1000);
begin
   qry := 'select count(*) from z_test_a where c_num = :1';

   execute immediate qry
   into o_count
   using i_tx;

  dbms_output.put_line(qry);
end;

我想知道的是,我怎樣才能看到確切的qryusing i_tx。我的意思是,如果輸入參數是i_tx = 2我如何select count(*) from z_test_a where c_num = 2在過程的輸出部分看到它,以便在出現錯誤時調試程式碼?這甚至可以看到確切的查詢嗎?在這個過程中,我現在在輸出頁面中得到的是:select count(*) from z_test_a where c_num = :1

提前致謝

REPLACE會有什麼好處嗎?見第 6 行和DBMS_OUTPUT.PUT_LINE.

SQL> create or replace procedure first_test(i_tx varchar2, o_count out number) is
 2    qry varchar2(1000);
 3  begin
 4      qry := 'select count(*) from z_test_a where c_num = :1';
 5
 6      dbms_output.put_line(replace(qry, ':1', i_tx));    --> like this
 7
 8      execute immediate qry into o_count using i_tx;
 9  end;
10  /

Procedure created.

SQL> declare
 2    l_cnt number;
 3  begin
 4    first_test(1, l_cnt);
 5  end;
 6  /
select count(*) from z_test_a where c_num = 1               --> result you want, I guess

PL/SQL procedure successfully completed.

SQL>

引用自:https://dba.stackexchange.com/questions/271629