MySQL自定義函數

原文連接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

MySQL自定義函數

函數與存儲過程相似,也是一組預先編譯好的SQL語句的集合,可是存儲過程能夠有0個或多個返回,函數就只能有一個返回sql

建立函數

#語法 參數列表包含兩部分 參數名和參數類型
#函數體必須有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('計算機一班');#函數調用

特別提醒一下:我在建立函數的時候出錯了less

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)函數

須要設置一下code

set global log_bin_trust_function_creators=TRUE;

因爲自己的博客百度沒有收錄,博客地址http://zhhll.icuget

相關文章
相關標籤/搜索