仅当参数不为0时才使用sql过滤器

时间:2018-01-15 13:22:33

标签: sql stored-procedures

您好我有以下程序:

CREATE PROCEDURE searchMembers(IN param1 INT, IN param2 INT, IN age INT)
  searchMembers:BEGIN
    SELECT * FROM members
      WHERE param1=param1 
      AND param2=param2
      AND age=age;
    END;

但我希望每个过滤器只有在params不等于零时才存在。例如,如果我运行CALL searchMembers(12, 24, 0);,则执行的查询应为

    SELECT * FROM members
      WHERE param1=param1 
      AND param2=param2;
    END;

任何想法如何做到这一点?

2 个答案:

答案 0 :(得分:1)

首先,为参数命名,使它们不与列名冲突。

然后,我会期待类似的事情:

CREATE PROCEDURE searchMembers (
    IN in_param1 INT,
    IN in_param2 INT,
    IN in_age INT
) AS
BEGIN
    SELECT m.*
    FROM members m
    WHERE (m.param1 = in_param1 OR in_param1 IS NULL) AND
          (m.param2 = in_param2 OR in_param2 IS NULL) AND
          (m.age = in_age OR in_age IS NULL);
END;

请注意,这使用NULL来表示所有。这是一个更典型的选择,但是如果你真正想要的话,你可以对0使用类似的逻辑。

答案 1 :(得分:0)

 SELECT * 
 FROM members
 WHERE (param1 = 0 or col1 = param1)
   AND (param2 = 0 or col2 = param2)
   AND (age_param = 0 or age = age_param)