简体   繁体   English

mysql存储过程动态where子句

[英]mysql Stored Procedure Dynamic Where Clause

I have the following query in a stored procedure: 我在存储过程中有以下查询:

SELECT * 
FROM tempProfile
WHERE 1 = 1
and case    when l_primarymailingaddress = 'address1' then find_in_set(add1_stateid,p_stateid) or p_stateid is NULL
            when l_primarymailingaddress = 'address2' then find_in_set(add2_stateid,p_stateid) or p_stateid is NULL end;

I am passing a list of IDs in on p_stateid. 我在p_stateid上传递ID列表。

The first case finds matches, but the second case doesn't. 第一种情况找到匹配项,但第二种情况找不到。

So if, for example, I pass in a 7, I do get back all results that have 7 in add1_stateid, the query is not returning results that have 7 in add2_stateid. 因此,例如,如果我传入7,则确实获得了add1_stateid中所有值为7的所有结果,则查询不会返回add2_stateid中具有7的结果。

Comparing against every example and description I can find this should work. 通过比较每个示例和说明,我可以发现它应该起作用。

Is anyone able to see what I am doing wrong here? 有人能看到我在做什么错吗?

Many Thanks 非常感谢

Ok - updated my answer to address where you specifically explained why you were using in_set and P_stateid. 好的-更新了我的答案,以解决您具体解释为什么使用in_set和P_stateid的问题。 Does breaking the Case statement into two and using an OR to compare each of them work? 将Case语句分成两个并使用OR进行比较是否可行?

SELECT * 
FROM tempProfile
WHERE 
case when l_primarymailingaddress = 'address1' AND find_in_set(add1_stateid,p_stateid) THEN 1 ELSE 0 END
OR
case when l_primarymailingaddress = 'address2' AND find_in_set(add2_stateid,p_stateid) THEN 1 ELSE 0 END
OR
p_stateid is NULL
;

2nd update - added another OR to return records when p_stateid is NULL 第二次更新-添加了另一个OR,以在p_stateid为NULL时返回记录

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM