天天看點

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 天生日進行提醒