MySQL(存储)过程 - 参数和查询

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19165324/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 19:02:44  来源:igfitidea点击:

MySQL (Stored) Procedure - parameters and query

mysqlstored-procedures

提问by Jon C.

I am trying to create a simple procedure with parameters.

我正在尝试创建一个带参数的简单过程。

CALL new_procedure('mode', 'ASC');

The first input is the column the second is the sort direction

第一个输入是列第二个是排序方向

DELIMITER $$

CREATE DEFINER=`root`@`localhost` PROCEDURE `new_procedure`(IN in_order_by_column varchar(20), in_order_by_direction char(4))
BEGIN

    DECLARE order_by varchar(30);
    SET @order_by = CONCAT('`', in_order_by_column, '` ', in_order_by_direction);
/*
    SELECT * FROM `common_tags` ORDER BY @order_by  LIMIT 5;
*/
    SELECT @order_by as 'c';

END

In the above example I have it only outputting the 2 parameters so I can see what's happening.

在上面的例子中,我只输出了 2 个参数,所以我可以看到发生了什么。

Result:

结果:

"c"
`mode` ASC

.

.

When I run the procedure with it's intended code, below.

当我使用它的预期代码运行该过程时,如下所示。

DELIMITER $$

CREATE DEFINER=`root`@`localhost` PROCEDURE `new_procedure`(IN in_order_by_column varchar(20), in_order_by_direction char(4))
BEGIN

    DECLARE order_by varchar(30);
    SET @order_by = CONCAT('`', in_order_by_column, '` ', in_order_by_direction);
    SELECT * FROM `common_tags` ORDER BY @order_by  LIMIT 5;

END

Results

结果

tags_id     data                mode        parent_id       position
1           Wood                2           13              6
2           Trippy              0           0               0
4           Artists             1           0               1
6           "Newest Additions"  1           0               11
12          "Natural Elements"  2           5               8

As you can see the results are not sorted by mode.

如您所见,结果未按 排序mode

Any help is appreciated.

任何帮助表示赞赏。

回答by BlitZ

Unfortunately, you need to PREPAREentire query in this case:

不幸的是,PREPARE在这种情况下您需要完整查询:

DELIMITER $$

DROP PROCEDURE IF EXISTS `new_procedure`$$

CREATE PROCEDURE `new_procedure`(IN in_order_by_column varchar(20), in_order_by_direction char(4))
BEGIN
    SET @buffer = CONCAT_WS('',
        'SELECT * FROM `common_tags` ORDER BY `', in_order_by_column, '` ', in_order_by_direction, ' LIMIT 5'
    );

    PREPARE stmt FROM @buffer;
    EXECUTE stmt;

    DEALLOCATE PREPARE stmt;
END$$

DELIMITER ;

NOTE:Described approach should be used very careful, because it is vulnurable to SQL Injection attacks, if used incorrectly.

注意:非常小心地使用所描述的方法,因为如果使用不当,它很容易受到 SQL 注入攻击。