简体   繁体   中英

Passing a table as variable for looping in mysql stored procedure

I want to store the result of my stored procedure based on the table passed as a parameter and then make a loop from it so that I can update the selected rows.

CREATE DEFINER=`root`@`localhost` PROCEDURE `close_transaction_procedure`(IN `tablename` VARCHAR(100), IN `businessdate_column` VARCHAR(40), IN `primary_number` VARCHAR(30), IN `lead_time` INT)
BEGIN

SET @strprd = CONCAT('SELECT ',primary_number, ', status_code FROM ',tablename,' WHERE ',businessdate_column ,' < DATE_SUB(NOW(), INTERVAL ', lead_time ,' DAY)');

PREPARE stmt1 FROM @strprd;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;

-- loop based on results of execute stmt1

END

You could try to update without a loop, using a temporary table to store the results of the select:

CREATE DEFINER=`root`@`localhost` PROCEDURE `close_transaction_procedure`(IN `tablename` VARCHAR(100), IN `businessdate_column` VARCHAR(40), IN `primary_number` VARCHAR(30), IN `lead_time` INT)
BEGIN

/* create a temporary table where you'll store your select's result */
DROP TEMPORARY TABLE IF EXISTS temp_records;
CREATE TEMPORARY TABLE IF NOT EXISTS temp_records
(
  primary_number VARCHAR(100),
  status_code VARCHAR(100)
);

/* store the result of the select into temp_records with the INSERT...SELECT construct */
SET @strprd = CONCAT('INSERT INTO temp_records(primary_number, status_code) SELECT ',primary_number, ', status_code FROM ',tablename,' WHERE ',businessdate_column ,' < DATE_SUB(NOW(), INTERVAL ', lead_time ,' DAY)');

PREPARE stmt1 FROM @strprd;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;

/* now that you have your result in temp_records table, you can update without a loop, using temp_records table as reference */

END

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM