我需要構造一個SQL子句動態,我看到一些例子只使用的情況下,但由於某種原因,我的源代碼不起作用。MySQL存儲過程與動態子句其中
有人可以幫助我嗎?
create procedure sp_test(in iduser bigint, in name varchar(50), in company varchar(50), in city varchar(50), in profession varchar(50))
begin
if not(name is null) then
begin
set name = '%' + lower(name) + '%';
end;
end if;
if not(company is null) then
begin
set company = '%' + lower(company) + '%';
end;
end if;
if not(city is null) then
begin
set city = '%' + lower(city) + '%';
end;
end if;
if not(profession is null) then
begin
set profession = '%' + lower(profession) + '%';
end;
end if;
select
usr.id_user,
usr.ds_icon,
usr.nm_user,
usr.ds_slug,
usr.ds_title,
usr.nm_company
from
tbl_user usr
left join tbl_profession pro on (pro.id_profession = usr.id_profession)
left join tbl_resume res on (res.id_user = usr.id_user)
where
(usr.ds_activation is null) and
usr.id_user <> iduser and
usr.id_user not in (select id_friend from tbl_user_friend where id_user = iduser) and
usr.id_user not in (select id_user from tbl_user_friend where id_friend = iduser) and
usr.id_user not in (select id_friend from tbl_user_friend_not_suggest where id_user = iduser) and
case when not(name is null) then
lower (usr.nm_user) like lower(name) or
end
case when not(company is null) then
lower (usr.nm_company) like lower(company) or
end
case when not(profession is null) then
lower (pro.nm_profession) like lower(profession) or
end
case when not(city is null) then
lower (res.ds_city) like lower(city) or
end
1 = 1
order by
usr.nm_user
limit
0,20
;
end$$
我猜理念的正確,我準備在字符串中使用%value%
把它用在SQL命令進行過濾,並檢查後,如果該值不爲空,我想將它添加到WHERE子句。