Mysql基于逻辑在存储过程中动态构建查询字符串

Ben*_*rie 8 mysql logic stored-procedures

目标是基于输入变量更改Mysql存储过程中的查询字符串.

像这样的东西:

CREATE DEFINER=`root`@`localhost` PROCEDURE `func`(type VARCHAR(15))
BEGIN
    SET @type = type;

    -- Check for the sort parameter
    if @type="asc" THEN
        SET @sort = " order by name asc";
    elseif @type="desc" THEN
        SET @sort = " order by name desc";
    else
        SET @sort ="";
    end if;

SELECT id, name from table @sort;

END    
Run Code Online (Sandbox Code Playgroud)

Ben*_*rie 16

解决方案是使用execute和concat:

CREATE DEFINER=`root`@`localhost` PROCEDURE `test`(input VARCHAR(15))
BEGIN
SET @input = input;

if @input="asc" then
    SET @sort = " order by ActivityLogKey asc";
elseif @input = "desc" then
    SET @sort = " order by ActivityLogKey desc";
else
    SET @sort ="";
end if;

SET @query = CONCAT('select * from activitylog ',@sort,' limit 0, 5');

PREPARE stmt FROM @query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

END
Run Code Online (Sandbox Code Playgroud)

  • 顺便说一句,即使不定义存储过程,execute 和 concat 也是解决方案;“但是如果你不改变...实现一个准备好的语句来生成动态 SQL”下的一个很好的例子。在[塔林的回答](https://dba.stackexchange.com/a/46447/70416)中。我发现这对于“一次性”(一次性)查询很有用。 (2认同)