最小化MySQL存储过程中的参数

时间:2013-08-24 19:50:46

标签: mysql stored-procedures parameters

我有一个存储过程,根据'foo'的值选择IDvars,并为它们分配包含foo的变量名。我可以这样做:

CALL db0.genericStoredProc(IDvar, "foo", "'foo'");

理想情况下,我只想写

CALL db0.genericStoredProc(IDvar, "foo");

如何利用bar,这样我不需要bar2参数? 以下是我的存储过程的相关部分。

DROP PROCEDURE IF EXISTS genericStoredProc;
DELIMITER $ $
CREATE PROCEDURE genericStoredProc(myID BIGINT(20) UNSIGNED, bar VARCHAR(5), bar2 VARCHAR(5))
BEGIN
SET @s = CONCAT('SELECT gt.name, gt.junk, gt.junkName, count(gt.idvar) as id_count,
        SUM(CASE 
            WHEN ot.offset <0 THEN 1 
            ELSE 0
        END) AS ', bar,'_id_count
    FROM genericTable gt
        LEFT JOIN otherTable ot ON gt.IDvar2 = ot.IDvar
    WHERE (gt.idvar = ', IDvar, ') AND (ot.prmtr = ', bar2, ')
GROUP BY gt.idvar');

PREPARE stmt FROM @s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END $$
DELIMITER ;

1 个答案:

答案 0 :(得分:1)

使用局部变量
如下所示

DELIMITER $ $
CREATE PROCEDURE genericStoredProc(myID BIGINT(20) UNSIGNED, bar VARCHAR(5))
BEGIN
DECLARE bar2 VARCHAR(5);
SET bar2=bar1 ;