mysql存储过程(循环插入),获取自增主键作为外键插入其他表

#定义存储过程
delimiter //
DROP PROCEDURE IF EXISTS  pro_addaccount;
##hosp_name医院名称,num_limit循环产生多少账号
CREATE PROCEDURE pro_addaccount(in hosp_name VARCHAR(50),in num_limit int)
BEGIN
DECLARE i int default 1;
DECLARE k int default 0;
DECLARE hosp_code VARCHAR(50) ;
DECLARE hosp_id int ;
DECLARE area_id int  ;
DECLARE account_id VARCHAR(50) ;
DECLARE result_account_id VARCHAR(50) ;
DECLARE role_id int ;
DECLARE Result int ;


  ##根据医院名称,查询医院code
set hosp_code = (select code from hosp where NAME=hosp_name); 
 ## 根据医院名称,查询医院id
set hosp_id = (select id from hosp where NAME=hosp_name);
 ##根据医院名称获取医院地市
set area_id = (select area_id from hosp where NAME=hosp_name);


WHILE i<=num_limit do
if (i <10) THEN  
  set account_id = CONCAT('00',i); 
   ELSEIF(i>=10) and (i<=99) THEN
  set account_id = CONCAT('0',i); 
  ELSE
  set account_id =''+i;
 end if ;
  
set result_account_id = CONCAT(hosp_code,account_id);


INSERT into sys_account(hosp_id,area_id,account,pwd,level,add_time,update_time,bind_state) values 
(hosp_id ,area_id ,result_account_id,'E10ADC3949BA59ABBE56E057F20F883E',1,now(),now(),0);
 
SET Result=LAST_INSERT_ID();
if(k<=5) THEN
 set role_id = 4;
ELSEIF(k>5)and(k<=50) THEN
set role_id = 2;
 Else 
set role_id=3;
end if; 


INSERT into sys_account_role(sys_role_id,sys_account_id) values 
(role_id,Result);
 


set k = k+1;
set i = i + 1;
 
END WHILE;
 
END
//

你可能感兴趣的:(mysql)