2013-05-20 88 views
0

我正在開發動態SQL查詢的第一步,我有一個關於論壇的問題。連接的select語句是否可以附加額外的連接語句(請參見下面的代碼)?Concat動態SQL查詢

use test; 
drop procedure if exists test.spds; 
delimiter $$ 
create procedure test.spds (
xage varchar(75), 
xgender varchar(2), 
xquery varchar(254)) 
begin 
set @xan:= REPLACE(xage,'''',''); 
set @xgn:= REPLACE(xgender,'''',''); 

set xquery:=concat('select count(*) from test.ratings where quota=1') 

if @xan is not null then 
xquery:=xquery concat(' and age in (',@xan,')') 

if @xgn is not null then 
xquery:=xquery concat(' and gender = ',@xgn,') 

end if; 

xquery=xquery concat(';'); 

prepare x1 from xquery; 
execute x1; 
deallocate prepare x1; 

end if; 
end $$ 

再次,這是我的第一次嘗試,所以也許我接近這一切都太簡單地和任何指導/建議,將不勝感激。謝謝!

回答

0

是你可以試試這個

if @xan is not null then 
    set xquery:=CONCAT(xquery, ' and age in (',@xan,')'); 
end if 
+0

感謝您的代碼,非常完美! – Atwp67