存储过程函数中的动态表名

2021-11-20 00:00:00 mysql stored-procedures

我编写了一个存储过程函数来从表中获取名称.问题是我希望将表名作为参数传入(有几个不同的表我需要使用这个函数):

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

我尝试使用过程代替,但我无法让它像函数一样只返回一个值.

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;

相关文章