gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 06:31:56 27 4
gpt4 key购买 nike

目标是根据输入变量更改 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

最佳答案

解决方案是使用执行和连接:

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

关于Mysql根据逻辑在存储过程中动态构建查询字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8549619/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com