Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To have Dynamic SQL in MySQL Stored Procedure

Tags:

dynamic

mysql

How do you build and use dynamic sql in a MySQL stored procedure?

like image 294
Brian Boatright Avatar asked Oct 10 '08 10:10

Brian Boatright


People also ask

Can we use dynamic SQL in 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.

Does MySQL support dynamic SQL?

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.

Can we create dynamic SQL using stored procedures containing parameters?

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.


2 Answers

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.

like image 191
TimoSolo Avatar answered Sep 22 '22 05:09

TimoSolo


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!

like image 24
Jason Stevenson Avatar answered Sep 19 '22 05:09

Jason Stevenson