我在mysql中的sproc中有动态查询的问题。
现在这个查询在我直接在phpmyadmin中执行时执行正常但是这似乎在执行时会出现语法错误。
BEGIN
SET @sql = 'set @my_id=24;
set @rank=0;
select * from (
(
select *, @rank:=@rank+1 as x from `list_content` where `id` > @my_id order by `id`)
union (select *, @rank:=@rank+1 as x from `list_content` where `id` < @my_id order by `id`)
) `list_content` WHERE `listId` = 15 limit 4';
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END
我真的需要这个以某种方式工作,因为我需要通过我传递的参数更改一些字段名称。
我得到的执行错误是......
MySQL said: #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'set @rank=0;
select * from (
(
select *, @rank:=@rank+1 as x from `list_c' at line 2
如果我可以在此环境之外执行它而没有任何问题,我认为这是一个准备查询的限制。
由于
答案 0 :(得分:1)
正如prepared statements上的mysql手册所说:
预准备语句的SQL语法不支持多语句 (即,单个字符串中的多个语句分隔; 字符)。
这意味着您在准备好的声明中不能有3个声明。但是,手册的同一部分也说明了
准备好的声明也是会议的全球性声明。
这意味着您可以将预处理语句之外的set语句移动到dtored proc的代码中,并且会话变量将在预准备语句中可用。
答案 1 :(得分:0)
您需要声明分隔符,否则;
将终止您的程序。像这样:
delimiter //
CREATE PROCEDURE whatever_you_named_it
BEGIN
SET @sql = 'set @my_id=24;
set @rank=0;
select * from (
(
select *, @rank:=@rank+1 as x from `list_content` where `id` > @my_id order by `id`)
union (select *, @rank:=@rank+1 as x from `list_content` where `id` < @my_id order by `id`)
) `list_content` WHERE `listId` = 15 limit 4';
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END
//
然后,您可以使用
将分隔符设置回;
delimiter ;
答案 2 :(得分:0)
将变量设置放入查询中。见@Shadow写的。
SET @sql = 'select * from (
(
select *, @rank:=@rank+1 as x from `list_content` where `id` > @my_id order by `id`)
union (select *, @rank:=@rank+1 as x from `list_content` where `id` < @my_id order by `id`)
) `list_content`
CROSS JOIN (SELECT @my_id:=24, @rank:=0) as init
WHERE `listId` = 15 limit 4';