Thursday, June 2, 2016

MYSQL - Store procedure to dynamically execute any SQL statement

We sometimes face situation in mysql store procedure where execution of SQL statement is not fixed and it changes based on the parameter.
Example : if we create temp tables during store procedure call and subsequently we want to use same table name for querying.

For such operation it become necessary to have some function which can allow us to execute ant SQL statement which is prepare on fly. Here is the definition of such Store Procedure.

In this example we are tying to get any sql statement as a string parameter and  let mysql prepare statement out of this string and execute it.


DELIMITER $$
DROP PROCEDURE IF EXISTS `EXEC_DYNAMIC_QRY` $$
CREATE PROCEDURE `EXEC_DYNAMIC_QRY`(IN qry text)
 
BEGIN
    set @qry=qry;
    PREPARE stmt FROM @qry;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
     
END $$
DELIMITER ;

How to execute ?
call EXEC_DYNAMIC_QRY("select 'demo' from dual");

No comments:

Post a Comment