我需要找到员工的周年纪念日和周年纪念日,并且每隔14天发送一次电子邮件。但是如果开始日期和结束日期在不同年份,我使用以下查询时会遇到12月最后一周的问题。
Select * from Resource
where (DATEPART(dayofyear,JoinDate)
BETWEEN DATEPART(dayofyear,GETDATE())
AND DATEPART(dayofyear,DateAdd(DAY,14,GETDATE())))
答案 0 :(得分:5)
您可以更新员工{{1>而不是与dayofyear
(在1月1日重置为零并且是您的查询在年终的14天内中断的原因)进行比较。为了查询的目的而成为当前年份,只是与实际日期进行比较
joindate
测试查询:
Select * from Resource
-- Add the number of years difference between joinDate and the current year
where DATEADD(year,DATEDIFF(Year,joinDate,GetDate()),JoinDate)
-- compare to range "today"
BETWEEN GetDate()
-- to 14 days from today
AND DATEADD(Day,14,GetDate())
-- duplicate for following year
OR DATEADD(year,DATEDIFF(Year,joinDate,GetDate())+1,JoinDate) -- 2016-1-1
BETWEEN GetDate()
AND DATEADD(Day,14,GetDate())
(H / T @Damien_The_Unbeliever进行简单修复)
以上正确选择了1月第一周的declare @joindate DATETIME='2012-1-1'
declare @today DATETIME = '2015-12-26'
SELECT @joinDate
where DATEADD(year,DATEDIFF(Year,@joinDate,@today),@JoinDate) -- 2015-1-1
BETWEEN @today -- 2015-12-26
AND DATEADD(Day,14,@today) -- 2016-01-09
OR DATEADD(year,DATEDIFF(Year,@joinDate,@today)+1,@JoinDate) -- 2016-1-1
BETWEEN @today -- 2015-12-26
AND DATEADD(Day,14,@today) -- 2016-01-09
(请注意我已经不得不捏造joinDate
,因为我没有设法创造时间旅行。)
上述解决方案还应解决隐藏在原始解决方案中的闰年问题。
<强>更新强>
您在评论中表达了选择@today
和AnniversaryDate
服务的要求,您需要应用一些Years
逻辑来确定是否为您的选择添加1(年份或日期)
CASE
答案 1 :(得分:0)
你可以这样做:
Select * from Resource
where DATEPART(dayofyear,JoinDate)
BETWEEN DATEPART(dayofyear,GETDATE())
AND DATEPART(dayofyear,DateAdd(DAY,14,GETDATE()))
OR
DATEPART(dayofyear,JoinDate)
BETWEEN (DATEPART(dayofyear,GETDATE()) + 365)
AND (DATEPART(dayofyear,DateAdd(DAY,14,GETDATE())) + 365)
答案 2 :(得分:0)
试试这个:
DECLARE @Today DATE = GETDATE() --'12/25/2013'
DECLARE @Duration INT = 14
;WITH Recur AS
(
SELECT @Today AS RecurDate
UNION ALL
SELECT DATEADD(DAY, 1, RecurDate)
FROM Recur
WHERE DATEDIFF(DAY, @Today, RecurDate)+1 < @Duration
)
SELECT
r.*
FROM
Resource r
JOIN Recur
ON CONVERT(VARCHAR(5), JoinDate, 101) = CONVERT(VARCHAR(5), RecurDate, 101)
WHERE JoinDate < @Today
答案 3 :(得分:-1)
您可以将SQL DATEADD() function与周数参数一起使用 以下是如何使用它:
DECLARE @date date = getdate()
Select * from Resource
where
JoinDate BETWEEN @date AND DATEADD(ww,2,@date)