存储过程函数中的动态表名称 [英] Dynamic table names in stored procedure function
问题描述
我编写了一个存储过程函数来从表中获取名称.麻烦的是,我希望将表名作为参数传递(我需要使用几个不同的表来使用此功能):
I've written a stored procedure function to get a name from a table. The trouble is that I want the table name to be passed in as a parameter (there are several different tables I need to use this function with):
DELIMITER $$
CREATE DEFINER=`root`@`localhost` FUNCTION `getName`(tableName VARCHAR(50), myId INT(11)) RETURNS VARCHAR(50)
begin
DECLARE myName VARCHAR(50);
SELECT
'name' INTO myName
FROM
tableName
WHERE
id=myId;
RETURN myName;
end
此方法有一个错误,因为它使用变量名"tableName"而不是变量的实际值.
This method has an error because it uses the variable name "tableName" instead of the actual value of the variable.
我可以通过使用CONCAT
这样的方法在程序中解决此问题:
I can work around this problem in a procedure by using a CONCAT
like this:
SET @GetName = CONCAT("
SELECT
'name'
FROM
",tableName,"
WHERE
id=",myId,";
");
PREPARE stmt FROM @GetName;
EXECUTE stmt;
...但是,当我尝试在函数中执行此操作时,我收到一条消息,提示:
...but, when I try to do this in a function I get a message saying:
存储函数或触发器中不允许使用动态SQL
Dynamic SQL is not allowed in stored function or trigger
我尝试改用 procedure ,但我无法像函数一样让它仅仅返回一个值.
I tried to use a procedure instead, but I couldn't get it to just return a value, like a function does.
因此,任何人都可以找到解决此问题的方法.看来这真是不可思议.
So, can anyone see a way to get around this problem. It seems incredibly basic really.
推荐答案
如果要使用标识符构建SQL语句,则需要使用准备好的语句;但是准备好的语句不能在函数中使用.因此,您可以使用OUT参数创建存储过程-
If you want to buld a SQL statement using identifiers, then you need to use prepared statements; but prepared statements cannot be used in functions. So, you can create a stored procedure with OUT parameter -
CREATE PROCEDURE getName
(IN tableName VARCHAR(50), IN myId INT(11), OUT myName VARCHAR(50))
BEGIN
SET @GetName =
CONCAT('SELECT name INTO @var1 FROM ', tableName, ' WHERE id=', myId);
PREPARE stmt FROM @GetName;
EXECUTE stmt;
SET myName = @var1;
END
使用示例-
SET @tableName = 'tbl';
SET @myId = 1005;
SET @name = NULL;
CALL getName(@tableName, @myId, @name);
SELECT @name;
这篇关于存储过程函数中的动态表名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!