Dynamic table names in stored procedure function

前端 未结 1 1487
一整个雨季
一整个雨季 2020-11-27 21:25

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 t

相关标签:
1条回答
  • 2020-11-27 21:58

    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;
    
    0 讨论(0)
提交回复
热议问题