我正在从表中获取查询并执行它们的存储过程中工作。 问题是我有一些带有单引号/双引号的查询,执行它们会引发错误。
过程
delimiter $$
drop procedure if exists run_change_ids_queries$$
create procedure run_change_ids_queries()
begin
declare s_query TEXT;
declare done bool default false;
declare c_queries cursor for
select `query` from `queries` WHERE `executed` = 0 ORDER BY `qry_id` ASC;
declare continue handler for not found set done = true;
open c_queries;
read_loop: loop
fetch c_queries into s_query;
if done then
leave read_loop;
end if;
-- run the query
set @sql = s_query;
prepare stmt from @sql;
execute stmt;
deallocate prepare stmt;
-- update executed flag on query
set @update = CONCAT('UPDATE `queries` SET `executed` = 1 WHERE `query` LIKE \'',@sql,'\';');
prepare stmt from @update;
execute stmt;
deallocate prepare stmt;
end loop;
end$$
查询 update urisegments as s inner join change_product_ids as p on concat('{"product_id":"', p.old_id, '"}') = s.primary_key_value set s.primary_key_value = CONCAT('{"product_id":', p.new_id, '"}') where s.app_namespace = 'Shop' and s.primary_key_value like '%product_id%';
引发错误:
[42000][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 '{"product_id":"', p.old_id, '"}') = s.primary_key_value set s.primary_key_value ' at line 1
变通办法#01
我已经尝试将单引号/双引号分别转义为\'
和\"
,但是它引发了另一个错误:
[42000][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 '\'{\"product_id\":\"\', p.old_id, \'\"}\') = s.primary_key_value set s.primary_k' at line 1
。
答案 0 :(得分:2)
不要尝试将查询连接到SQL中。准备好的语句可以包含占位符,当您使用EXECUTE
语句时可以将其填充。
set @update = 'UPDATE `queries` SET `executed` = 1 WHERE `query` = ?');
prepare stmt from @update;
execute stmt USING @sql;
答案 1 :(得分:0)
该语句未转义。 所有单/双引号都应转义。
update urisegments as s
inner join change_product_ids as p on concat(\'{\"product_id\":\"\', p.old_id, \'\"}\') = s.primary_key_value
set s.primary_key_value = CONCAT(\'{\"product_id\":\', p.new_id, \'\"}\')
where s.app_namespace = \'Shop\' and s.primary_key_value like \'%product_id%\';
答案 2 :(得分:0)
而不是测试查询,而是测试其ID:
... WHERE qry_id = ?
(将该列添加到开头的SELECT
。)