玖叶教程网

前端编程开发入门

mysql用户变量的定义使用

用户变量,可以定义在命令行、函数、存储过程中,断开连接时,变量消失,使用起来十分方便。

用户变量的定义

用户变量的定义,直接使用@标识符。下面的语句定义一个变量count,并进行赋值。

set @count = 1;
set @count := 5;
select 8 into @count;

查看变量的值

select @count;

用户变量的使用实例

t_record表记录收入和支出的明细记录,使用下面的sql可以统计出每个月的总收入和总支出,当然主要是为了演示用户变量的如何使用。

set @sid=0;
set @eid=0; 
set @d1='2021-02-01';
set @d2='2021-03-01';
select ID into @sid from t_record where AddTime >=@d1 limit 1;	
select ID into @eid from t_record where AddTime > @d2 limit 1;
	
-- 每月收入总数
select '总收入' as tag, cast(sum(income) AS decimal(11,2)) cnt, @d2 
from t_record where id>=@sid and id<@eid 
union 
-- 每月支出总数
select '总支出' as tag, cast(sum(outlay) AS decimal(11,2)) as cnt, @d2 
from t_record where id>=@sid and id<@eid 

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言