doulin2555 2015-05-05 08:21
浏览 78
已采纳

将表作为变量传递给mysql存储过程中的循环

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
  • 写回答

1条回答 默认 最新

  • duanchui1955 2015-05-05 08:57
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料