天天看点

SQL 中在表内查询近 3 天内生日的学生信息(注意闰年的情况)

下图是测试数据截图

SQL 中在表内查询近 3 天内生日的学生信息(注意闰年的情况)

解决方案

declare @nowdate datetime
set @nowdate=convert(datetime,GETDATE())
 select 考生号,姓名,convert(varchar(10),生日,120)birth from 
	(select *, (case when not(year(@nowdate)%4=0 and year(@nowdate)%100<>0 or year(@nowdate)%400=0)
	-- 判断是否为闰年
	and month(生日)=2 and day(生日)=29
	-- 判断考生生日是否为 2 月 29 日 
	then
	-- 修改日期,转化为今年的年月日作条件进行判断,输出不是闰年,考生生日为 2 月 29 日的今年生日加 1的结果
	convert(datetime,convert(varchar(4),year(@nowdate))+substring(convert(varchar(10),dateadd(day,1,生日),120),5,10))
	else
	-- 修改日期,转化为今年的年月日作条件进行判断,输出是闰年,考生生日不为 2 月 29 日的今年生日的结果
	convert(datetime,convert(varchar(4),year(@nowdate))+substring(convert(varchar(10),生日,120),5,10)) 
	end)今年生日日期 from student
	)a
where datediff(day,@nowdate,今年生日日期)>=0 and datediff(day,@nowdate,今年生日日期)<3
-- 距离今天还有 3 天生日进行提醒