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;