1.一個簡單的函數
需求:編寫函數,傳入一個用戶uid,返回用戶的uname
delimiter $$
create function getuname(my_uid int) returns varchar(32) CHARSET utf8
reads sql data # 表示子程序包含讀數據的語句,但不包含寫數據的語句
begin
declare my_uname varchar(32) DEFAULT '';
select uname into my_uname from temp_user where uid=my_uid;
RETURN my_uname;
end;
$$
delimiter ;
函數的基本特徵:
1.創建函數使用create function 函數名(參數) returns 返回類型
2.函數體放在begin和end直接
3.return指定函數的返回值(必須要有return返回值)
4.函數調用:select getuname();
2.自定義函數示例01
需求:輸入用戶ID,獲得accountid,uid,uname組合的UUID值,在全區遊戲中作爲用戶的唯一標識
CREATE FUNCTION getuuid(my_uid int) RETURNS varchar(32) CHARSET utf8
READS SQL DATA # 表示子程序包含讀數據的語句,但不包含寫數據的語句
BEGIN
declare uuid varchar(32) DEFAULT '';
select concat(accountid,'_',uid,'_',uname) into uuid from users where uid=my_uid;
RETURN uuid;
END
3.自定義函數示例02
需求:輸入參數uid,計算該uid所在賬號下的所有遊戲角色的金幣總量
CREATE FUNCTION statgold(my_uid int) RETURNS int(11)
READS SQL DATA
BEGIN
declare my_accountid int DEFAULT 0 ;
declare gold_sum int DEFAULT 0;
select accountid into my_accountid from temp_user where uid=my_uid;
select sum(gold) into gold_sum from temp_user where accountid=my_accountid;
RETURN gold_sum;
END