这是我的代码,但它显示为null,而今天是星期五。但我想最后一个工作日。
-- Insert statements for procedure here
--Below is the param you would pass
DECLARE @dateToEvaluate date=GETDATE();
--Routine
DECLARE @startDate date=CAST('1/1/'+CAST(YEAR(@dateToEvaluate) AS char(4)) AS date); -- let's get the first of the year
WITH
tally(n) AS (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL))-1 FROM sys.all_columns),
dates AS (
SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS dt_id,
DATEADD(DAY,n,@startDate) AS dt,
DATENAME(WEEKDAY,DATEADD(DAY,n,@startdate)) AS dt_name
FROM tally
WHERE n<366 --arbitrary
AND DATEPART(WEEKDAY,DATEADD(DAY,n,@startDate)) NOT IN (6)
AND DATEADD(DAY,n,@startDate) NOT IN (SELECT CAST(HolidayDate AS date) FROM Holiday)),
curr_id(id) AS (SELECT dt_id FROM dates WHERE dt=@dateToEvaluate)
SELECT d.dt
FROM dates AS d
CROSS JOIN
curr_id c
WHERE d.dt_id+1=c.id
答案 0 :(得分:0)
dates
表格中没有任何星期五日期。将NOT IN (6)
更改为NOT IN (1, 7)
。这将从日期表中删除星期六和星期日。
答案 1 :(得分:0)
以下代码将采用任何日期并“向后走”以查找不在@holidays表中的上一周(M-F)。
declare @currentdate datetime = '2015-03-22'
declare @holidays table (holiday datetime)
insert @holidays values ('2015-03-20')
;with cte as (
select
@currentdate k
union all
select
dateadd(day, -1, k)
from cte
where
k = @currentdate
or ((datepart(dw, k) + @@DATEFIRST - 1 - 1) % 7) + 1 > 5 --determine day of week independent of culture
or k in (select holiday from @holidays)
)
select min(k) from cte