3

I'm trying to use a user-defined variable to stand-in for a table name so that I can just use mysql and not require any other languages.

This example is way simplistic - the real script uses the table name a LOT and it'd be easier for end-users to be able to just change the variable rather than search/replace.

SET @tablename = 'mytable';
SELECT * FROM @tablename;

This won't work, but shows the end result I need.

6
  • 1
    For users to beable to perform an action from your database by using table names they define themselves.. You are opening up your schema layout... I would avoid doing this.. Commented Jan 27, 2013 at 22:44
  • This is probably a bad idea. Why do you want to do this? Commented Jan 27, 2013 at 22:44
  • This is a data conversion script we have to provide for users, we really don't want to. The table names for the old system entirely depend on what the user entered, and we need to know what they are otherwise our import script won't work. The other software was horribly designed IMO Commented Jan 27, 2013 at 22:47
  • This could pose a massive security flaw.. I would recommend a re-make of your application. Commented Jan 27, 2013 at 23:09
  • I agree with all the comments here. What if the user picks information_schema as the table name? This would expose almost all your database information. Commented Jan 28, 2013 at 1:05

1 Answer 1

5

Use prepared statements:

SET @tablename = 'mytable';

SET @query = CONCAT('SELECT * FROM ', @mytable);
PREPARE stmt FROM @query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

If your actual query is far more complicated, you could wrap the building of the query in some stored function:

DELIMITER //
CREATE FUNCTION GetQuery(tableName VARCHAR(50)) RETURNS VARCHAR(100)
BEGIN
    DECLARE finalQuery VARCHAR(100);
    SET finalQuery = CONCAT('SELECT * FROM ', tableName);
    -- do something fancier with finalQuery here
    RETURN finalQuery;
END //
DELIMITER ;

SET @query = GetQuery('mytable');
PREPARE stmt FROM @query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

Even better: do everything in a stored procedure:

DELIMITER //
CREATE PROCEDURE QueryTable(tableName VARCHAR(50))
BEGIN
    SET @finalQuery = CONCAT('SELECT * FROM ', tableName);
    PREPARE stmt FROM @finalQuery;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
    SET @finalQuery = NULL;
END //
DELIMITER ;

CALL QueryTable('mytable');
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.