儲存過程動態匹配引數

2021-10-18 23:44:22 字數 1357 閱讀 4738

之前在寫儲存過程遇到的乙個事情,記錄一下

儲存過程需要接收五個引數,這五個引數是在同一條sql中,並且每乙個引數不一定會存在值,如果當前的這個值不存在的時候不進行where條件的匹配

按照以往的做法都是先把原來的sql先用變數進行接收,然後用if條件再進行匹配,當這個引數符合我們的條件時候繼續拼接到後面,最後用 execute immediate進行執行。

v_createsql clob;

begin

v_createsql :='select * from test where 1=1';

if a<> null then v_createsql = v_createsql+ 'and a='+a end if;

if b<> null then v_createsql = v_createsql+ 'and b='+b end if;

if c<> null then v_createsql = v_createsql+ 'and c='+c end if;

if d<> null then v_createsql = v_createsql+ 'and d='+d end if;

if e<> null then v_createsql = v_createsql+ 'and e='+e end if;

execute immediate v_createsql;

end;

後來在同事的sql中發現乙個更有趣的寫法就分享出來

利用sql 中 or 和and的特性,採用短路的想法進行實現

當單個條件的時候

select * from test where 1=1 or( pid is not null and pid = pid );

當多個條件的時候

where

( (p_names is null or p_names='' and 1=1)

or (p_names is not null and p_names!='' and p_name like '%'||p_names'%')

)and(

(branchid is null or branchid='' and 1=1)

or(branchid is not null and branchid!='' and b_id = branchid)

) 當or條件中有乙個條件符合的時候則會執行and後面的條件,當or前面的條件不滿足的時候,就不會執行and的查詢條件,我們就可以把判斷寫在or當中,把我們的匹配的內容寫在and裡面,這個做法的弊端就是必須要把所有的條件寫出來。因為當我們使用and的時候後面就必須要使用條件,當引數不滿足的時候也要有條件,所以需要新增乙個1=1

儲存過程動態引數

create or replace procedure testdynamicparams p cmbno in varchar2,p trade date in varchar2 is cursor testcursor is select cmbno,trade date,securno,tur...

mysql儲存過程動態引數查詢

1 動態sql,即動態引數 在儲存過程中,想要直接用表名變數做引數,動態執行sql,不能直接寫 12 3456 7createprocedure tablenamechar 20 begin select fromtablename end mysql 不支援表名作為變數,這樣會直接將變數名 tab...

Mysql 儲存過程處理動態引數

刪除 drop procedure if exists up common select 建立 create procedure up common select in t name varchar 50 begin declare v sql varchar 500 set v sql conca...