Stored Functions in Mysql
1. Define variables
set variable name = variable value
Note: To distinguish between system variables and user-defined variables, add the @ symbol in front of user-defined variables
You can get the current variable through select
2. select into syntax to inject variable values
select a,b,c into @a,@b,@c syntax
If select returns a multi-line syntax, mysql will report an error or assign the last line
In sql total assignment, you can use @who :=xxx assignment
3. Built-in functions
format, Now, from_unixtime(), unix_timestamp(), charLength() are related to encoding, length()
concat,substring
The following defines several common types of custom functions
1. No parameter custom function
delimiter $$ create function sayHello() returns varchar(25) begin return 'Hello ShanShanBox.com'; end $$ delimiter ;
Notice:
The function is bound to the database and can be accessed using the database name and method name
The function must have a return value, and returns must be added with S
2. With if logical judgment
delimiter $$ create function func1() returns varchar(5) begin if hour(now()) > 17 then return 'late'; else return 'early'; end if; end $$ delimiter ;
3. With a while loop function
delimiter $$ create function func2() returns int begin set @i = 1; set @sum = 0; while @i <= 10 do set @sum = @sum + @i; set @i = @i + 1; end while; return @sum; end $$ delimiter ;
4. Loop Control
leave is equivalent to break to terminate the loop
iterate is equivalent to continue, skipping the current loop for the next loop
In the while loop, the loop is not controlled according to the position of leave and iterate, but is determined by the label of the loop
So what is the label of the loop, in fact, I can't tell, just look at the code
delimiter $$ create function func3() returns int begin set @i = 1; set @sum = 0; w:while @i <= 10 do if @i = 5 then leave w; end if; set @sum = @sum + @i; set @i = @i + 1; end while; return @sum; end $$ delimiter ;
See, w: is the label of the while loop, what a beautiful expression
5. Custom functions with parameters
delimiter $$ create function func4(username varchar(20)) returns varchar(25) begin return concat('hello ',username); end $$ delimiter ;
The above are a few simple custom functions
It's not easy to learn, do it and cherish it