I wrote a stored procedure function to get the name from the table. The problem is that I want the table name to be passed as a parameter (for this function, you need to use several different tables):
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 the variable name "tableName" is used instead of the actual value of the variable.
I can get around this problem in the procedure using CONCAT as follows:
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:
Dynamic SQL is not allowed in a stored function or trigger
I tried to use the procedure instead, but I could not get it to simply return the value, as the function does.
So, can anyone see a way around this problem. It is really incredibly simple.
source share