自定义函数
-
自定义无参函数
-
create function myselect3() returns TINYINT begin declare test_var TINYINT ; set test_var = 6 ; return test_var; end; /* This function has none of DETERMINISTIC, NO SQL, or READS SQL DATA in its declaration and binary log 其中在function里面,只有 DETERMINISTIC, NO SQL 和 READS SQL DATA 被支持。如果我们开启了 bin-log, 我们就必须为我们的function指定一个参数。 解决:set global log_bin_trust_function_creators=TRUE; */
-
变量
1. 变量的声明与赋值
1. 创建全局变量
1. 使用set关键字:要求变量名使用@符号标记:set @var_test = '变量' ; 变量的作用越:当前窗口,变量的查看使用select关键字 加 变量名 显示在表格中:select @var_test ;
2. set 关键字只能创建全局变量,全局变量名必须使用@标识作为开头
3. 变量的访问:select var_name ;
2. 创建局部变量
1. 使用declare关键字:declare var_name varchar(10) default 'hello' ;
2. 修改或者赋值使用set关键字:set var_name = '你好' ;
3. 变量的赋值与修改:select column_name into var_name from table_name where :也可以使用符号冒号等于赋值;
1. select column_name := var_name from table_name where
4. 局部变量的创建不能直接使用begin end ;需要放在存储过程或者方法中
存储过程
-
创建存储过程
-
-- 存储过程中才可以使用declare关键字声明变量 -- declare var_a CHAR(10) DEFAULT 'aa' ; -- 创建mysql的存储过程中不能有 or replace 关键字 create procedure test_procedure01 () begin -- declare var_a CHAR(10) ; set @var_a = '变量set' ; select @var_a ; end ; -- 调用存储过程 call test_procedure01() ; select name into @var_a from student where id = 09 ; select @var_a ; -- set 关键字只能创建全局变量,全局变量名必须使用@标识作为开头 -- 删除存储过程 drop procedure test_procedure01 ;
-
mysql的存储过程和Oracle的存储过程区别
1. Oracle使用了as/is 关键字,mysql中没有 2. Oracle的关键字变量的声明可以放在begin外面,mysql的声明变量关键字只能放在begin end 里面 3. Oracle的存储过程调用使用的是begin end ;mysql存储过程的调用使用的是关键字:call + procedure_name () ; 4. 创建存储过程时: or replace 不可用 5. 存储过程的参数:三种:in 、out 、inout 、
函数
-
创建函数
-
/* 1. 函数必须带有括号,使用returns关键字声明返回值类型 2. 变量的声明和赋值是分开的, 3.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; 4. 变量类型长度问题,如果是字符串varchar或者char,一定要设置字符长度,包括返回值returns,不是return */ create function my_func( var_name VARCHAR(10)) returns VARCHAR(4) begin declare test_var VARCHAR(10) default 'hello' ; set test_var = var_name ; return test_var; end; select my_func('你好') from dual ; -- 设置数据库 某些属性值 set global log_bin_trust_function_creators=TRUE; -- 删除函数,使用 关键字 if exists ,解决如果函数名称不存在而报错问题 drop function if exists my_func ;