mysql 創建表和轉移數據

樓主在開發工程中遇到這樣一個需求,要求把數據在點擊完成以後,根據表名和數據id'把數據封存起來,如果存在表就去插入如果不存再就先創建表再去更新,樓主寫了一個存儲過程


drop procedure if exists p_createtb;  
CREATE PROCEDURE p_createtb(IN patientUniqueId varchar(32),IN topicId INT)  
BEGIN  
     declare    tbname varchar(100);
     declare    tbname1 varchar(100);
     declare i_count int default 0;  
    declare done int default false;  
    declare cur cursor for select topic_copy_name from dcfphryun.tb_research_topic_copy_table ;  
    declare continue HANDLER for not found set done = true;  
    set tbname1="";
     set i_count = 0;
    open cur;  
    read_loop:loop  
    fetch cur into tbname;   
    if done then  
        leave read_loop;    
    end if; 
        set tbname1=concat(topicId,"_",substring(tbname,locate('_',tbname,4)+1));
       select count(*) into i_count from `INFORMATION_SCHEMA`.`TABLES` where `TABLE_SCHEMA`='dcfphr_topic' and `TABLE_NAME`=tbname1;
       if i_count<=0 then
           set @sql = concat("CREATE  TABLE dcfphr_topic.",tbname1," as","(select * from `dcfphryun`.",tbname," where patient_unique_id = '",patientUniqueId,"')");
           prepare stmt from @sql;
           execute stmt;
        end if;
       if i_count>=1 then 
     set @sql = concat("insert into dcfphr_topic.",tbname1,"(select * from `dcfphryun`.",tbname," where patient_unique_id = '",patientUniqueId,"')");
              prepare stmt from @sql;
              execute stmt;
end if;
    end loop;  
    close cur;   
END; 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章