C 练习实例4 之mysql实现

本文介绍了一个SQL函数,用于计算输入的特定日期是一年中的第几天,包括闰年的处理。通过案例分析,详细解释了如何进行月份累加,并在特定条件下调整闰年的影响。

题目:输入某年某月某日,判断这一天是这一年的第几天?

程序分析:以3月5日为例,应该先把前两个月的加起来,然后再加上5天即本年的第几天,特殊情况,闰年且输入月份大于3时需考虑多加一天。

drop  FUNCTION if exists test;

create  FUNCTION test( year int, month int, day int)
RETURNS int
BEGIN
		
    declare  sum ,leap int DEFAULT 0;
 
		-- 判断输入的日期是否正确
		if   DATE_FORMAT(CONCAT(year,'-',month,'-',day),'%Y%m%d')  IS NULL then 
				return null;
		end if ;

     case month
        when 1 then set sum=0; 
        when 2 then set sum=31; 
        when 3 then set sum=59;
        when 4 then set sum=90; 
        when 5 then set sum=120; 
        when 6 then set sum=151; 
        when 7 then set sum=181; 
        when 8 then set sum=212; 
        when 9 then set sum=243; 
        when 10 then set sum=273; 
        when 11 then set sum=304; 
        when 12 then set sum=334;
		 end case ;
    
		set sum=sum+day;  
   
		if year%400 = 0 or (year%4=0 and year%100<>0)   then
       set leap=1;
     else  
       set leap=0;
     end if;

    if leap=1 and month>2 then
        set sum=sum+1;
     end if;
    
	return sum;
		
end;

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值