原文鏈接http://zhhll.icu/2021/01/03/%E6%95%B0%E6%8D%AE%E5%BA%93/%E5%85%B3%E7%B3%BB%E5%9E%8B%E6%95%B0%E6%8D%AE%E5%BA%93/MySQL/MySQL%E8%87%AA%E5%AE%9A%E4%B9%89%E5%87%BD%E6%95%B0/
MySQL自定義函式
函式與存盤程序類似,也是一組預先編譯好的SQL陳述句的集合,但是存盤程序可以有0個或多個回傳,函式就只能有一個回傳
創建函式
#語法 引數串列包含兩部分 引數名和引數型別
#函式體必須有return陳述句 且每個sql陳述句后要以;結尾 所以需要使用delimiter來重新設定結束標記
#函式體中只有一句話時可以省略begin end
create function 函式名(引數串列) returns 回傳值型別
begin
函式體
end
執行函式
select 函式名(引數串列)
查看函式
show create function 函式名;
洗掉函式
drop function 函式名;
示例
delimiter $
create function myfunc(class_name varchar(20)) returns int
begin
declare c int default 0; #設定區域變數,作為回傳值
select count(s.id) into c # 將查詢結果賦給區域變數
from class c
join student s on c.id = s.classid
where c.name = class_name;
return c; #回傳
end $
delimiter ;
select myfunc('計算機一班');#函式呼叫
特別提醒一下:我在創建函式的時候出錯了
ERROR 1418 (HY000): This function has none of DETERMINISTIC, NO SQL, or READS SQL DATA in its declaration and binary logging is enabled (you might want to use the less safe log_bin_trust_function_creators variable)
需要設定一下
set global log_bin_trust_function_creators=TRUE;
由于本身的博客百度沒有收錄,博客地址http://zhhll.icu
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/259381.html
標籤:MySQL
上一篇:抖音直播如何做資料分析?
下一篇:Redis-第八章節-應用場景
