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
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With