Pass parameters to MySQL script

后端 未结 6 2008
無奈伤痛
無奈伤痛 2020-12-09 04:05

I have a MySQL script file named query1.sql which contains:

select * FROM $(tblName) LIMIT 10;

I am in MySQL console, how do I

6条回答
  •  不思量自难忘°
    2020-12-09 04:18

    You can use user variables to achieve the behaviour you describe. As you use the variable as a schema identifier, not a data value, you'll have to use a prepared statement so you can compose the query dynamically.

    query1.sql:

    SET @query = CONCAT('Select * FROM ', @tblName, ' LIMIT 10');
    PREPARE stmt FROM @query;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
    

    Invoked as

    mysql> SET @tblName = 'Users'; \. query1.sql
    

提交回复
热议问题