1.遞迴
delimiter $$;
drop procedure if exists `rentmgr`.`tmp`$$
** 引數說明:zjjg_id上級機構編號,result是輸出變數
** 函式說明:遞迴返回本級機構和下級所有機構編號,通過","分隔
create definer=`root`@`localhost` procedure `tmp`(in zgjg_id char(16),out result varchar(1000))
begin
declare _done int default 0;
declare jg_id1 char(250);
/*游標申明*/
declare cursor1 cursor for select jg_id from jgxxb where sjjg_id=zgjg_id;
declare continue handler for sqlstate '02000' set _done = 1;
set @@max_sp_recursion_depth = 10;
/*當為空值時返回本級結點*/
if result is null then
set result=zgjg_id;
end if;
/*開啟游標*/
open cursor1;
repeat
fetch cursor1 into jg_id1;
if not _done then
/*注意:如果想用result做為引數傳入的話,儲存過程不識別認為空值,這樣遞迴就會失敗!
解決方案:採用就建乙個臨時變數的方式,取得資料後用連線方式。@符即是為臨時儲存使用不需要申明。
set result=concat(result,',',jg_id1);
call tmp(jg_id1,result);
*/call tmp(jg_id1,@tmp1);
set result=concat(result,',',@tmp1);
end if;
until _done end repeat;
close cursor1;
end$$
delimiter ;$$
2.交叉表
delimiter $$;
drop procedure if exists `rentmgr`.`cross_tab`$$
create definer=`root`@`localhost` procedure `cross_tab`(vsourcetab varchar(2000),vgroupbyfield varchar(50),vtransformcol varchar(50),vpivotcol varchar(50))
begin
declare vfunction varchar(50)default "sum" ;/*求和函式*/
declare strsql varchar(8000); /*求和sql*/
declare done int default 0; /*游標判斷*/
declare strsum varchar(3000); /*求分組的總和*/
declare pcols varchar(100);
declare temp_ny varchar(10);
/*申明游標*/
declare cur1 cursor for select distinct ny from query_area order by ny;
declare continue handler for sqlstate '02000' set done = 1;
set strsql ='';
set strsum='';
set pcols='';
set strsql="select jg_id";/*select分組字段*/
open cur1;
repeat
fetch cur1 into temp_ny;/*年份*/
if not done then
/*求年月份*/
set strsql=concat(strsql,",sum(case when ny='",temp_ny,"' then mzh else 0 end) as ",temp_ny);
/*求年月份總和使用*/
set strsum=concat(strsum,"+case when a.",temp_ny," is null then 0 else a.",temp_ny," end");
end if;
until done end repeat;
close cur1;
/*內層sql求取各年份的值*/
set strsql=concat(strsql," from query_area group by jg_id");
set strsql=concat("(",strsql,")a");
/*求年月份總和*/
set strsum=concat("(0",strsum,") as total");
set strsql=concat("select a.*,",strsum," from ",strsql);
set @a=strsql;
/*拼湊得到的可執行的sql語句*/
select @a;
/*執行拼湊得到的可執行的sql語句*/
prepare stmt1 from @a;
execute stmt1 ;
end$$
delimiter ;$$
mysql儲存過程表 mysql儲存過程和表命令
show procedure status 2.顯示某個儲存過程的詳細資訊 sp為儲存過程名稱 show create procedure sp 3.顯示當前庫中所有表 show tables 4.顯示某個表的建表語句 test為表名 show create table test 5.刪除儲存過程 ...
MySQL儲存過程遞迴呼叫
有分類表tb system category,結構如下 create table tb system category id int 11 not null auto increment,c parent id int 11 not null,c name varchar 50 not null,c...
mysql儲存過程使用遞迴
實現功能為查詢節點所有子節點同時更新子節點資料,用遞迴進行處理。測試時始終報錯 error code 1456 set max sp recursion depth 100 下面是mysql遞迴呼叫的源 delimiter in uid varchar 225 in ncount int begin...