mysql之函式 整理

2021-07-09 12:14:42 字數 2331 閱讀 9063

新建:

createfunction function_name(引數列表)

returns返回值型別

函式體乙個函式應該屬於某個資料庫,可以使用db_name.funciton_name的形式執行當前函式所屬資料庫,否則為當前資料庫。

多條語句應該使用begin end語句塊包含。

注意,一定要有return返回值語句。

刪除:dropfunction if exists function_name;

檢視:showfunction status like 『partten』

showcreate function function_name;

修改:alterfunction function_name 函式選項。

dropfunction if exists hello; -- 刪掉已經存在的

delimiter$$     -- 定義分隔符,必須要有,可以不是$$

create  function hello( s varchar(30))   -- 多個引數用,分割 引數的型別必須是mysql列存在的型別

returnsvarchar(255)                    -- 指定返回值型別,如果你不確定返回文字長度,可以使用text

begin

declare str varchar(255) default 'hello';  -- 定義乙個變數,可以指定預設值

set str = concat(str,s);                    -- 設定改邊變數的值

return str;                                 -- 返回值

end$$                                          -- 注意看清楚了,這個end後面有你在前面定義的分割符號

delimiter$$                                    -- 好,這裡結束。

delimiter$$

dropfunction if exists `onlinefunction`$$

createfunction `onlinefunction`(rrrr varchar(50)) returns varchar(255)

begin

if(rrrr='online')then return '上線';end if;

end$$

delimiter;

第一行delimiter 定義乙個結束識別符號,因為mysql預設是以分號作為sql語句的結束符的,

而函式體內部要用到分號,所以會跟預設的sql結束符發生衝突,所以需要先定義乙個其他的符號作為sql的結束符。

沒有加這個定義的話,錯誤碼: 1064

有時候mysql不能建立自定義函式是因為該功能2未開啟

輸入 show variables like '%func%'; 命令

會看到 log_bin_trust_function_creators 的狀態,如果是off表示自定義函式功能是關閉的

輸入命令 set global log_bin_trust_function_creators=1;

可將 log_bin_trust_function_creators 開啟自定義函式功能

但是這樣設定是乙個臨時的方案,因為mysql自動重啟後狀態又會變為off,所以需要在

在服務啟動時加上 「--log-bin-trust-function-creators=1 」引數。

或在my.ini(my.cnf)中的[mysqld]區段中加上 log-bin-trust-function-creators=1。

delimiter//

createfunction namebyt()

returnschar(50)    -- returns

return(select name from t3 where id=2);      --return

delimiter;

delimiter$$ 

dropfunction if exists `sp_test`.`getdate` $$ 

createfunction `sp_test`.`getdate`(gdate datetime)

returnsvarchar(255) 

begin 

declarex varchar(255) default ''; 

setx= date_format(gdate,'%y年%m月%d日%h時%i分%s秒'); 

returnx; 

end$$ 

delimiter;

以上內容,摘自很多部落格,在此謝過。。。

MySql函式整理

1 round x,d 四捨五入。round x 其實就是round x,0 也就是預設d為0 selectround 110.35,1 110.4 2 truncate x,d 直接擷取需要保留的小數字 selecttruncate 110.35,1 110.3 3 format x,d 四捨五入...

mysql函式整理

一.字串函式 1.拼接字串concat str1,str2.select concat hello word 2.包含字元個數length str select length hello,word!3.擷取字串 left str,len 返回字串str的左端len個字元 right str,len ...

Mysql常用函式整理

1.字串函式 length 資料 字串位元組數 char length 資料 字串長度 left 資料,x 字串左邊的x個字元 right 資料,x 字串右邊的x個字元 concat 資料1,資料2,資料3.拼接字串 strcmp 資料1,資料2 比較字串 前者大於後者為1,等於為0,小於為 1 s...