使用变量作为表名的mysql错误

前端之家收集整理的这篇文章主要介绍了使用变量作为表名的mysql错误前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

为什么我收到此错误

CREATE DEFINER=`root`@`localhost` PROCEDURE `selectrecords`(tablename varchar(50))
begin
set @table_name=tablename;
set @sql_text=concat('Select * from @table_name');
prepare statement from @sql_text;
execute statement;
deallocate prepare statement;
end

错误

....to use near '@table_name' at line 1

我的代码是正确的,但我不明白为什么….

最佳答案
我想你的意思是,

CREATE PROCEDURE `selectrecords`(tablename varchar(50))
begin
    set @sql_text = concat('Select * from ',tablename);
    prepare statement from @sql_text;
    execute statement;
    deallocate prepare statement;
end

即使在动态sql中,也不能参数化表名和列名,因此您唯一的选择是与字符串连接.只有值可以放在占位符中.

> MySQL PREPARE syntax

更新1

CREATE PROCEDURE `selectrecords`(tablename varchar(50))
begin
    set @val = idnumber;
    set @sql_text = concat('Select * from ',tablename,' WHERE id = ?');
    prepare statement from @sql_text;
    execute statement USING @val;
    deallocate prepare statement;
end
原文链接:https://www.f2er.com/mysql/433133.html

猜你在找的MySQL相关文章