Executing dynamic queries, where the SQL statement itself is constructed at runtime, is commonly performed in MSSQL using the EXEC stored procedure. However, MySQL lacks a direct equivalent.
To execute dynamic queries in MySQL, one approach is to construct the query string as a variable and then use the PREPARE and EXECUTE statements.
The following code demonstrates how to execute a dynamic query in MySQL:
SET @queryString = ( SELECT CONCAT('INSERT INTO user_group (`group_id`,`user_id`) VALUES ', www.vals) as res FROM ( SELECT GROUP_CONCAT(qwe.asd SEPARATOR ',') as vals FROM ( SELECT CONCAT('(59,', user_id, ')') as asd FROM access WHERE residency = 9 ) as qwe ) as www ); PREPARE stmt FROM @queryString; EXECUTE stmt; DEALLOCATE PREPARE stmt; SET @asd = NULL;
By following this approach, MySQL can execute dynamic queries even though the query itself is not known in advance.
The above is the detailed content of How to Execute Dynamic Queries in MySQL?. For more information, please follow other related articles on the PHP Chinese website!