MySQL Stored Functions - Dynamic/Variable Table & Column Names

后端 未结 1 1281
悲哀的现实
悲哀的现实 2020-12-11 13:03

I\'m learning stored procedures/functions/triggers in MySQL this morning and I\'m having some problems trying to use variable table and column names in queries.



        
相关标签:
1条回答
  • 2020-12-11 13:43

    Use User/Global Vars for this along with PREPARE & EXECUTE:

    SET @columnName='myColumn';
    SET @tableName='myTable';
    SET @whatEver='requiredValue';
    
    SET @query=CONCAT('SELECT ', @columnName, ' FROM ', @tableName, ' WHERE Column=', @whatEver);
    PREPARE QUERY FROM @QUERY;
    EXECUTE QUERY;
    

    Haven't tested this EXACT code but something along these lines will work. Also has to be inside a Procedure, cannot be used with a function or trigger, if anyone has a soloution for that then please post.

    0 讨论(0)
提交回复
热议问题