mysql存储过程执行动态sql

delimiter //
drop PROCEDURE IF EXISTS attentBatch;
create PROCEDURE attentBatch(userid INT,num INT)
BEGIN
DECLARE self_tab_index INT;
DECLARE done INT DEFAULT 0;
DECLARE tabindex INT;
DECLARE fansuserid INT;
DECLARE sql1 VARCHAR(500);
DECLARE sql2 VARCHAR(500);
DECLARE cur_user CURSOR FOR SELECT user_id FROM em_user limit num; -- 定义光标
DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = 1; -- 处理异常
SET self_tab_index = userid % 4;

OPEN cur_user;
REPEAT
FETCH cur_user into fansuserid;
SET tabindex = fansuserid % 4; -- 分表算法


SET sql1 = CONCAT("INSERT IGNORE INTO em_user_relation",tabindex,"(user_id,follow_id,type)","VALUES(",fansuserid,',',userid,',',1,")");
SET @sql1 = sql1; -- 注意很重要,将连成成的字符串赋值给一个变量(可以之前没有定义,但要以@开头
PREPARE stmt FROM @sql1; -- 预处理需要执行的动态SQL,其中stmt是一个变量  
EXECUTE stmt; -- 执行sql语句
DEALLOCATE PREPARE stmt; -- 释放预处理段


SET sql2 = CONCAT("INSERT IGNORE INTO em_user_relation",self_tab_index,"(user_id,follow_id,type)","VALUES(",userid,',',fansuserid,',',0,")");
SET @sql2 = sql2;
PREPARE stmt1 FROM @sql2;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;

UNTIL done END REPEAT;
SELECT sql2; -- 测试sql
CLOSE cur_user;
END
//
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值