zoukankan      html  css  js  c++  java
  • Mysql 使用存储过程合并多个表数据

    drop procedure if exists mergeTable;
    CREATE PROCEDURE mergeTable()
    BEGIN
    
        #定义变量
        declare temp_table_name varchar(20);
        declare total int default 0;
        declare done int default false;
        #游标数据来源  查询出你想要合并的表名称
        declare cur cursor for SELECT table_name
                               from information_schema.TABLES
                               where table_name LIKE '%user%'
                               group by table_name;
        #定义标记结束
        declare continue HANDLER for not found set done = true;
    
        drop table if exists temp_table;
        #创建临时表
        CREATE temporary TABLE `temp_table`
        (
            `id`   int(11)    NOT NULL,
            `name` int(11)    NOT NULL,
            `type` tinyint(2) NOT NULL
        );
    
    
        set total = 0;
        open cur;
        #变量赋值
        fetch cur into temp_table_name;
        while(not done)
            do
                #复制表数据到临时表
                set @sqlStr = CONCAT('INSERT INTO temp_table (`id`, `name`, `type`)
            SELECT `id`, `name`, `type`
         FROM  ', temp_table_name);
    
                PREPARE stmt from @sqlStr;
                #执行sql
                EXECUTE stmt;
    
                fetch cur into temp_table_name;
            end while;
    
        close cur;
        #统计临时表个数
        select count(1) from temp_table;
    END;
    
    #执行临时表
    call mergeTable();
    
  • 相关阅读:
    如何根据关键字匹配度排序
    LeetCode 题解目录
    Spring Boot、Cloucd 学习示例
    JavaScript工具库
    使用 Docker 部署 Spring Boot 项目
    LeetCode 寻找两个有序数组的中位数
    Bean 生命周期
    Dubbo支持的协议
    MySQL组成模块
    Spring Boot 搭建TCP Server
  • 原文地址:https://www.cnblogs.com/wlphp/p/15155410.html
Copyright © 2011-2022 走看看