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

报告相同问题?

悬赏问题

  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画