Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass parameters to MySQL script

Tags:

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

select * FROM $(tblName) LIMIT 10; 

I am in MySQL console, how do I pass the parameter to the script? This does not forward the variable:

mysql> \. query1.sql -v tblName=Users 
like image 252
decapo Avatar asked Dec 31 '12 06:12

decapo


People also ask

How do I pass a variable to a MySQL script?

First Step: Use of Set command. SET @anyVariableName − = 'yourValue'; Second Step: Pass a variable to a MySQL script. Display all records from the table using select statement.

How do I get parameters in MySQL?

Parameter is represented by MySql. MySqlParameter class. All parameters that take part in query execution constitute a collection that can be accessed through MySqlCommand. Parameters property.

What is parameter in MySQL?

The MySQL Stored procedure parameter has three modes: IN, OUT, and INOUT. When we declare an IN type parameter, the application must pass an argument to the stored procedure. It is a default mode. The OUT type parameter, the stored procedure returns a final output generated by SQL Statements.

How do I create a variable in MySQL?

MySQL variable assignment There are two ways to assign a value to a user-defined variable. You can use either := or = as the assignment operator in the SET statement. For example, the statement assigns number 100 to the variable @counter. The second way to assign a value to a variable is to use the SELECT statement.


1 Answers

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 
like image 134
MvG Avatar answered Sep 19 '22 20:09

MvG