Dynamic SQL in MySQL Stored Procedures
MySQL versions 5.0.13 and later provide the ability to construct and execute dynamic SQL statements within stored procedures. This allows for greater flexibility and customization in your database operations.
How to Construct Dynamic SQL in a Stored Procedure
To build dynamic SQL, you can use the following steps:
Example:
Consider the following stored procedure that selects a column from a table based on user-provided inputs:
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 ;
To use the stored procedure, you can call it with the desired table and column names as follows:
CALL dynamic('customers', 'name');
This will execute the following SQL statement:
SELECT name FROM customers;
Note:
The above is the detailed content of How to Use Dynamic SQL in MySQL Stored Procedures?. For more information, please follow other related articles on the PHP Chinese website!