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

This method has an error because it uses the variable name "tableName" instead of the actual value of the variable.

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:

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.


Solution 1:

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

Using example -

SET @tableName = 'tbl';
SET @myId = 1005;
SET @name = NULL;
CALL getName(@tableName, @myId, @name);
SELECT @name;