Interpreting the value of TEXT as a part of a query?
Consid开发者_JAVA技巧er this example below in MySQL.
DECLARE myText TEXT;
SET myText = "myColumn";
SELECT * FROM myTable WHERE myText = "myValue";
In the above scenario, it wouldn't select any columns, because the value of myText is never "myValue". However, what I really want to do is to interpret the value of myText as a part of the query, so that the final query that it executes is:
SELECT * FROM myTable WHERE myColumn = "myValue";
How can I do that?
Use prepared statements
SET @myText = "myColumn";
SET @s = CONCAT('SELECT * FROM myTable WHERE ', @myText, ' = "myValue" ');
PREPARE stmt1 FROM @s;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;
精彩评论