函數與存儲過程相似,也是一組預先編譯好的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