我正在尝试构建存储过程,动态构建查询取决于提供的参数
对于初始要求我有2个可切换的参数,第3个是可选的,我做了这个
PROCEDURE `myProcedure`(IN pred1 int(11),IN pred2 varchar(45),IN pred3 datetime)
BEGIN
DECLARE idx int(11) DEFAULT 0;
set @query := ' SELECT * FROM `mytable` where ';
SET @a = "" ;
IF pred1 is not null THEN
SET @a = pred1;
SET @query = CONCAT(@query,' and field1 = ? ' );
END IF;
IF pred2 is not null THEN
SET @a = pred2;
SET @query = CONCAT(@query,' and field2 = ? ' );
END IF;
IF pred3 is not null THEN
SET @b = pred3;
SET @query = CONCAT(@query,' and field3 = ? ' );
END IF;
PREPARE stmt FROM @query;
IF pred3 is not null THEN
EXECUTE stmt USING @a, @b
ELSE
EXECUTE stmt USING @a;
END IF;
END
现在我的规格发生变化,所有参数都是可选的,保存像我这样的问题最佳做法是什么?