MySQL - 在Update上使用动态sql

时间:2015-02-25 09:03:51

标签: mysql stored-procedures dynamic-sql

我正在使用MySQL 5.6并尝试一个简单的过程,如下所示。

drop procedure if exists procsBook;

DELIMITER $$

CREATE PROCEDURE procsBook()

main:begin

DECLARE abc VARCHAR(256);

DECLARE def VARCHAR(256);

DECLARE field_name2 VARCHAR(256);

DECLARE field_names VARCHAR(256);

DECLARE bkid BIGINT(20);

SET abc:= NULL;

SET def:= NULL;

SET field_name2:= NULL;

SET field_names:= NULL;

SET bkid:= 0;

select a.field_name,b.column_name into abc,def from  table1 a join table2 b where a.field_label=b.field_label and b.table_name='Table13' and b.section_name='English' group by a.field_name limit 1;

IF(abc is not null)
then

IF (SUBSTRING(abc,7,1)=1)

THEN

SELECT book1,bookId INTO field_names,bkid FROM shelf1 WHERE rowstate=0;

SET @vSelectQury = CONCAT('update shelf2 set def = ' , field_names, ' where book_id = ', bkid);
PREPARE vDynamicSSql FROM @vSelectQury;

EXECUTE vDynamicSSql;

DEALLOCATE PREPARE vDynamicSSql;

END IF;

END IF;

END $$
DELIMITER ;

呼叫:

call procsBook();

这会引发以下错误:

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 'where book_id = 22' at line 1

请帮忙吗?

1 个答案:

答案 0 :(得分:0)

我认为您需要在field_names周围添加引号。

  

SET @vSelectQury = CONCAT('更新shelf2 set',def,' = \'',field_names,   ' \' book_id =',bkid);准备vDynamicSSql FROM @vSelectQury;

(或者如果您的设置不同,则可能需要更改转换为'字符)

已更新您不应直接使用def,但在这种情况下请使用def的值。