您好,欢迎来到舟合美食网。
搜索
您的当前位置:首页mysql中自定义函数编程_MySQL

mysql中自定义函数编程_MySQL

来源:舟合美食网


参考学生表

create table join_student(

stu_id int not null auto_increment,

stu_no char(10),

class_id int not null,

stu_name varchar(10),

stu_info text,

primary key (stu_id)

);

计算新增学号

drop function if existssno;

delimiter $$ #在包含有语句块时 可以更换语句结束符“;” 为“$$”

create function sno(c_id int)returns char(10)

begin

declare last_no char(10); #声明一个局部变量 用来保存当前最大的学号, 如果没有就为null

declare class_name char(10);

select stu_no from join_student where class_id=c_id order by stu_no desc limit 1 into last_no;

if last_no is null then #如果为空代表当前班级没有学生 从1开始,获得班级名字

return concat ((select c_name from join_class where id=c_id into class_name),'001'); #concat() 函数的作用是连接字符串。

else

return concat(left(last_no,7),lpad(right(last_no,3) + 1, 3, '0'));

end if;

#return @last_no;

end

$$

delimiter ;

随机获得学生名字。

drop function if exists sname;

delimiter $$

create function sname() returns char(2)

begin

declare first_name char(16) default '赵钱孙李周吴郑王冯陈褚卫蒋沈韩杨';

declare last_name char(10) default '甲乙丙丁戊己庚辛壬癸';

declare full_name char(2);

set full_name=concat(substring(first_name,floor(rand()*16+1), 1), substring(last_name,floor(rand()*10+1), 1));

return full_name;

end

$$

delimiter ;

========================================================================================

mysql常用内置函数

数值函数

Abs(X),绝对值abs(-10.9) = 10

Format(X,D),格式化千分位数值format(1234567.456, 2) =1,234,567.46

Ceil(X),向上取整ceil(10.1) = 11

Floor(X),向下取整floor (10.1) = 10

Round(X),四舍五入去整

Mod(M,N) M%N M MOD N 求余 10%3=1

Pi(),获得圆周率

Pow(M,N) M^N

Sqrt(X),算术平方根

Rand(),随机数

TRUNCATE(X,D) 截取D位小数

时间日期函数

Now(),current_timestamp(); 当前日期时间

Current_date();当前日期

current_time();当前时间

Date(‘yyyy-mm-dd HH;ii:ss’);获取日期部分

Time(‘yyyy-mm-dd HH;ii:ss’);获取时间部分

Date_format(‘yyyy-mm-dd HH;ii:ss’,’%D %y %a %d %m %b %j');

Unix_timestamp();获得unix时间戳

From_unixtime();//从时间戳获得时间

字符串函数

LENGTH(string ) //string长度,字节

CHAR_LENGTH(string) //string的字符个数

SUBSTRING(str ,position [,length ]) //从str的position开始,取length个字符

REPLACE(str ,search_str ,replace_str) //在str中用replace_str替换search_str

INSTR(string ,substring ) //返回substring首次在string中出现的位置

CONCAT(string [,... ]) //连接字串

CHARSET(str) //返回字串字符集

LCASE(string ) //转换成小写

LEFT(string ,length ) //从string2中的左边起取length个字符

LOAD_FILE(file_name) //从文件读取内容

LOCATE(substring , string [,start_position ]) //同INSTR,但可指定开始位置

LPAD(string ,length ,pad ) //重复用pad加在string开头,直到字串长度为length

LTRIM(string ) //去除前端空格

REPEAT(string ,count ) //重复count次

RPAD(string ,length ,pad) //在str后用pad补充,直到长度为length

RTRIM(string ) //去除后端空格

STRCMP(string1 ,string2 ) //逐字符比较两字串大小

流程函数:

CASE WHEN [condition]THEN result[WHEN [condition]THEN result ...][ELSE result]END 多分支

IF(expr1,expr2,expr3) 双分支。

聚合函数

Count()

Sum();

Max();

Min();

Avg();

Group_concat()

其他常用函数

Md5();

Default();

Copyright © 2019- zhouheie.com 版权所有

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务