How do you build and use dynamic sql in a MySQL stored procedure?
Using dynamic SQL inside stored procedures This stored procedure is used to search for products based on different columns like name, color, productid, and the product number. The dynamic SQL statement is constructed based on the input parameters passed to the stored procedure and is executed by the EXEC command.
MySQL supports Dynamic SQL with the help of EXECUTE and PREPARE statements. Suppose you have a scenario where you need to pass table name as parameter value and returns all column values, you can use Dynamic SQL.
Dynamic SQL allows stored procedures to “write” or dynamically generate their SQL statements. The most common use case for dynamic SQL is stored procedures with optional parameters in the WHERE clause.
After 5.0.13, in stored procedures, you can use dynamic SQL:
delimiter // CREATE PROCEDURE dynamic(IN tbl CHAR(64), IN col CHAR(64)) BEGIN SET @s = CONCAT('SELECT ',col,' FROM ',tbl ); PREPARE stmt FROM @s; EXECUTE stmt; DEALLOCATE PREPARE stmt; END // delimiter ;
Dynamic SQL does not work in functions or triggers. See the MySQL documentation for more uses.
I don't believe MySQL supports dynamic sql. You can do "prepared" statements which is similar, but different.
Here is an example:
mysql> PREPARE stmt FROM -> 'select count(*) -> from information_schema.schemata -> where schema_name = ? or schema_name = ?' ; Query OK, 0 rows affected (0.00 sec) Statement prepared mysql> EXECUTE stmt -> USING @schema1,@schema2 +----------+ | count(*) | +----------+ | 2 | +----------+ 1 row in set (0.00 sec) mysql> DEALLOCATE PREPARE stmt;
The prepared statements are often used to see an execution plan for a given query. Since they are executed with the execute command and the sql can be assigned to a variable you can approximate the some of the same behavior as dynamic sql.
Here is a good link about this:
Don't forget to deallocate the stmt
using the last line!
Good Luck!
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