mysql 多日誌表結果集合拼接預存程序,mysql預存程序

來源:互聯網
上載者:User

mysql 多日誌表結果集合拼接預存程序,mysql預存程序

通常單天的日誌 只記錄當天的日誌資訊,如果需要查看一月內的日誌資訊需要對每天的日誌表結果集合進行拼接,通常用到 union 。

儲存過程:

drop PROCEDURE if  EXISTS unionSp;DELIMITER //create procedure unionSp(sTime varchar(32), eTime varchar(32),tchema varchar(32))begindeclare sqlVar varchar(1024000);declare rest int;declare tableName varchar(1024);set rest = 100;set sqlVar='';while rest > 0 do   set sTime = (select DATE_FORMAT((select ADDDATE(sTime,1)),'%Y%m%d')); set tableName=CONCAT('tbl_req_',sTime); select count(1) from information_schema.tables where table_name = tableName  and TABLE_SCHEMA=tchema into @cnt; if @cnt != 0 thenif rest=1 then set sqlVar=CONCAT(sqlVar,' SELECT DISTINCT channel_id,app_id from tbl_req_',sTime);ELSE set sqlVar=CONCAT(sqlVar,' SELECT DISTINCT channel_id,app_id from tbl_req_',sTime,' UNION');END IF;END if;set rest = DATEDIFF(eTime,sTime);END while;set @v_s=sqlVar;prepare stmt from @v_s;EXECUTE stmt;DEALLOCATE PREPARE stmt;end;// DELIMITER;call unionSp('20140730','20140930','biz_date')

union:聯合的意思,即把兩次或多次查詢結果合并起來。
 要求:兩次查詢的列數必須一致
 推薦:列的類型可以不一樣,但推薦查詢的每一列,想對應的類型以一樣
 可以來自多張表的資料:多次sql語句取出的列名可以不一致,此時以第一個sql語句的列名為準。
 如果不同的語句中取出的行,有完全相同(這裡表示的是每個列的值都相同),那麼union會將相同的行合并,最終只保留一行。也可以這樣理解,union會去掉重複的行。
如果不想去掉重複的行,可以使用union all 



MYSQL怎把預存程序所返回的結果集插入到表?

從預存程序返回表類型的值也有二種:1.預存程序使用浮標參數,即同時指定CURSOR VARYING OUTPUT項.調用者可以使用while及fetch迴圈遍曆該浮標.2.直接將預存程序返回的結果集插入到表中,即使用insert into 表名 exec 預存程序.此種方式中注意預存程序返回的結果集列與insert的列要完全對應,可以在insert中指定列名來保證對應關係.------------------------------------------------------------------------------測試:----------------------------------------------------------------------------------建立測試用的暫存資料表create table #tmp (colx int,coly int)insert into #tmp values(1,2)insert into #tmp values(2,3)insert into #tmp values(3,4)select * from #tmpGO----建立返回遊標的預存程序create proc sp_c @cur CURSOR VARYING OUTPUTASbeginset @cur = CURSOR for select colx from #tmpopen @cur /*該過程返回遊標,該遊標為colx列的查詢結果*/endGO----建立返回表的預存程序create proc sp_dasselect coly from #tmp /*該過程返回coly列的查詢結果*/go----建立用於調用以上二個預存程序的預存程序create proc sp_easbegindeclare @x intdeclare @cur cursor----接收遊標,並遍曆遊標EXEC sp_c @cur OUTPUTfetch next from @cur into @xwhile (@@FETCH_STATUS = 0)beginprint @xfetch next from @cur into @xENDclose @curdeallocate @cur----將預存程序返回的列值再重新插入源表中insert into #tmp(coly) EXEC sp_dselect * from #tmpendGOEXEC sp_edrop proc sp_cdrop proc sp_d
 
mysql怎兩個預存程序返回的結果集放入同一表中

不能合并到同一個預存程序嗎?如果不能的話,只能建立一張表,然後兩個過程都操作這張表。
 

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.