如何从动态MYSQL存储过程中的Null参数值获取结果

时间:2017-06-22 08:17:59

标签: mysql sql

我的表格名称 table_abc 包含颜色 name varchar(255) NOT NULL,store_id INT(11) NOT NULL,brand varchar(255) NOT NULL,status INT(11) NOT NULL

表 -

 name   | store_id  | brand |       status
    dress      1         only           1
    dress      2        vero moda       1
    dress      2         ZARA           1
    dress      2        vero moda       1
    dress      3         only           1
    dress      3        vero moda       1
    dress      1         only           1
    dress      2        ZARA            1

如果在参数中传递NULL或空''值,我想要动态结果,那么它可以将该特定参数的整行作为结果给出。例如:

 delimiter //
    DROP PROCEDURE IF EXISTS sp_test//
    CREATE PROCEDURE sp_test(
    list_of_name VARCHAR(255), 
    list_of_ids VARCHAR(100), 
    list_of_brand VARCHAR(100) )
    BEGIN
         SET @query := CONCAT("SELECT name,store_id,brand,status FROM `table_abc`  
    WHERE name in (" , list_of_name ,") AND status='1' 
    AND store_id in (" , list_of_ids OR list_of_ids IS NULL, ")
     AND brand in (" , list_of_brand , ") 
     ORDER BY RAND() LIMIT 0,16");
         PREPARE stmt FROM @query;
         EXECUTE stmt;
         DEALLOCATE PREPARE stmt;
         END//
         delimiter ;

我们尝试使用null值参数获取结果。但是store_id无法在此过程中工作。或null也无效。 请帮助

  • mysql> call sp_test("'dress'",'1,2,3',"'only','vero moda','ZARA'");
  • mysql> call sp_test("'dress'",null,"'only','vero moda','ZARA'");
  • mysql> call sp_test("'dress'",'null',"'only','vero moda','ZARA'");

1 个答案:

答案 0 :(得分:1)

尝试这样的事情(我没有测试过脚本,所以你可能需要稍微调整一下)

 delimiter //
    DROP PROCEDURE IF EXISTS sp_test//
    CREATE PROCEDURE sp_test(
    list_of_name VARCHAR(255), 
    list_of_ids VARCHAR(100), 
    list_of_brand VARCHAR(100) )
    BEGIN
         SET @query := CONCAT("SELECT name,store_id,brand,status FROM `table_abc`  
    WHERE name in (" , list_of_name ,") AND status='1' 
     + CASE WHEN ISNULL(list_of_ids,'') <> '' THEN "AND store_id in (" + list_of_ids + ") 
     AND brand in (" , list_of_brand , ") 
     ORDER BY RAND() LIMIT 0,16");
         PREPARE stmt FROM @query;
         EXECUTE stmt;
         DEALLOCATE PREPARE stmt;
         END//
         delimiter ;