mysql function

1. declare vs set

1.1.declare 声明一个变量,这个变量是局部变量

DECLARE var_name[,...] type [DEFAULT value]

一般在sp的begin/end之间有效,超出这个范围就无效了,declare 变量必须放在begin/end之间也就是存储过程中,如果不初始化那么默认值为NULL

declare 定义的变量需要出现在变量定义的最前端。

它的赋值只能通过set或者select into进行赋值,

注意:declare 定义的变量即使和set定义的变量名称相同,也不为同一个变量。

CREATE DEFINER=`root`@`localhost` PROCEDURE `GetAll`()
BEGIN
DECLARE t1 int default 1;
set t1=t1+1;
set @t1=@t1+1;
select t1,@t1;
END;


1.2.set是一个赋值语句,

SET @var_name = expr [, @var_name = expr]

这个变量是在session范围内有效。如果不初始化,那么没有默认值

他在同一个会话的过程中只需要赋值一遍,并且被所有会话共享,存储过程外的sql也能使用,每个session对应于一个连接客户端,不同的客户端对应不同的session。

1.3.预处理变量只能使用set

set @var=text

prepare sq from @var

execute sq

deallocate prepare sql.


2.COALESCE  vs IFNull

The main difference between the two is that IFNULL function takes two arguments and returns the first one if it's not NULL or the second if the first one is NULL.


COALESCE function can take two or more parameters and returns the first non-NULL parameter, or NULL if all parameters are null, for example:


SELECT IFNULL('some value', 'some other value');

-> returns 'some value'


SELECT IFNULL(NULL,'some other value');

-> returns 'some other value'


SELECT COALESCE(NULL, 'some other value');

-> returns 'some other value' - equivalent of the IFNULL function


SELECT COALESCE(NULL, 'some value', 'some other value');

-> returns 'some value'


SELECT COALESCE(NULL, NULL, NULL, NULL, 'first non-null value');

-> returns 'first non-null value'

3. rtrim(str)

    移除str尾部的空格

4.substring_index(str,delimit,count)

当count>0的时候从左到右返回delimit在str中第count次出现之前的字符串

如果str中的delimit少于count,那么全部返回,如果count为0,那么返回空字符串

当count<0的时候从右往左返回delimit在str中第count(自右往左数)次出现的字符串

如果str中少于abs(count)个数是,全部返回,当count=0时,返回空

参考资料:

https://blog.csdn.net/seteor/article/details/17682551

https://blog.csdn.net/rdarda/article/details/7878836

https://hi.baidu.com/jingminglang/item/cdbe5fd95354bff2cb0c399f

https://stackoverflow.com/questions/18528468/what-is-the-difference-bewteen-ifnull-and-coalesce-in-mysql

https://www.w3resource.com/mysql/string-functions/mysql-substring_index-function.php


评论

© ftutor / Powered by LOFTER