|
存儲過程
delimiter //
drop procedure if exists reku_2_search_charActionLog_noLogin_count; -- 如果存在則刪除
create definer `pay_center`@`localhost` procedure reku_2_search_charActionLog_noLogin_count(start_date varchar(20),end_date varchar(20)) --definer `pay_center`@`localhost` 相當(dāng)于只 允許本機的pay_center權(quán)限的用戶創(chuàng)建
begin lable_exit: -- 這兒可以理解為開啟跳轉(zhuǎn)
begin
if start_date is not null and end_date is not null then -- 如果 start_date 和end_date 參數(shù)不為空的話 定義用戶變量,全局的
set @start_date = unix_timestamp(start_date); 此函數(shù) 相當(dāng)于把具體時間 轉(zhuǎn)換為時間戳 和php中的 strtotime()一個意思
set @end_date = unix_timestamp(end_date);
else
if start_date is null then
set @start_date = unix_timestamp(date_format(current_timestamp(),'%Y-%m-%d 00:00:00'));
set @end_date = unix_timestamp(end_date);
end if;
if end_date is null then
set @start_date = unix_timestamp(start_date);
set @end_date = unix_timestamp(date_format(current_timestamp(),'%Y-%m-%d 23:59:59'));
end if;
end if;
if @start_date - @end_date > 0 then
select '時間不對';
leave lable_exit;
end if;
set @query = 'select count(*) as cnt from game_forbidinfo where phpTime >=? and phpTime <=?';
prepare stmt_sql_str from @query; --預(yù)定義sql
execute stmt_sql_str using @start_date,@end_date; 執(zhí)行預(yù)定義同時 按照順序 給? 賦值
end lable_exit; 跳出
end;
drop procedure if exists reku_2_search_charActionLog_noLogin_res;
create procedure reku_2_search_charActionLog_noLogin_res(start_date varchar(20),end_date varchar(20),limits varchar(40))
begin
set @limit = limits;
set @query = "select gf.*, ru.rolename from game_forbidinfo as gf left join role_user as ru on gf.charid=ru.roleid where phpTime >=? and phpTime <=? limit ?";
prepare stmt_sql_str from @query;
execute stmt_sql_str using @start_date,@end_date,@limit;
end;
delimiter ;
刪除 存儲過程:drop procedure reku_2_search_charActionLog_noLogin_res;
查看 所有存儲過程: show procedure status where db='reku';
查看 指定存儲過程代碼: show create procedure where 'reku.reku_2_search_charActionLog_noLogin_res';
存儲過程和存儲函數(shù)的不同點在于 編寫存儲代碼 應(yīng)用的環(huán)境(同時語法有兩處不同 第一行多了一個:returns 類型 最后一行 返回 return 值 ) ,當(dāng)編寫存儲代碼 只是為了 返回 一個 狀態(tài) 或者一個標(biāo)示時,建議用 存儲函數(shù)
create function factorypp (num int)
returns int
DETERMINISTIC --必須加這個
begin
declare result int default 1;
while num >0 do
set result = num * result;
set num = num -1;
end while;
return result; --返回結(jié)果
end;
調(diào)用存儲函數(shù) 用 select (注意:不用call)
select factorypp (10);
delimiter //
create definer `pay_center`@`localhost` function factorypp(num int)
begin
declare result int(11) default 1;
while num >0 do
set result = num * result;
set num = num -1;
end while;
return result;
end;
//
delimiter ;
返回結(jié)果為一個數(shù)字。
存儲過程優(yōu)點:
. 簡化了應(yīng)用程序(php ,Java,asp)的編寫 ,
. 因為存儲過程是在服務(wù)器內(nèi)部執(zhí)行 離數(shù)據(jù)最近,不需要帶寬,和網(wǎng)絡(luò)延遲的影響。(通過配合{內(nèi)存臨時表}有可能提高一些where條件的查詢速度)
.也能得到應(yīng)用程序的復(fù)用,比如 分頁邏輯寫成存儲過程,
.不需要每次執(zhí)行時 進行解析 和編譯,創(chuàng)建時已經(jīng)進行了編譯。
缺點:
.不調(diào)好調(diào)試。
.更改應(yīng)用程序 和 表結(jié)構(gòu)邏輯時。
.MySQL 里的函數(shù)有限,
存儲函數(shù) 優(yōu)缺點 同上。
.
|