我在这个网站上的代码在一年中的所有星期如下,我应该填写星期日,开始日期为星期六和结束日期为星期五。当一周结束时,它应该进入下一周的日期。 我怎么能实现这一点请帮助我。
DECLARE @Year INT=2013;
DECLARE @start DATE;
--DECLARE @WK INT=2
SET @start = DATEADD(YEAR, @Year-1900, 0);
;WITH n AS
(
SELECT TOP (366) -- in case of leap year
TDate = DATEADD(DAY, ROW_NUMBER() OVER (ORDER BY name)-1, @start)
FROM sys.all_objects
),
x AS
(
SELECT md = MIN(TDate) FROM n
WHERE DATEPART(WEEKDAY, TDate) = 7 -- assuming DATEFIRST is SATURDAY
),
y(TDate,wk) AS
(
SELECT n.TDate, ((DATEPART(DAYOFYEAR,n.TDate)-
DATEDIFF(DAY, @start,x.md)-1)/7)+1
FROM n CROSS JOIN x
WHERE n.TDate >= x.md
AND n.TDate < DATEADD(YEAR, 1, @start)
)
SELECT [date] = TDate, [week] = wk
FROM y WHERE wk < 53
ORDER BY [date];
答案 0 :(得分:0)
不确定你在问什么,但根据你上面的查询,这将给出周数,基于星期六是一周的第一天,2013年:
DECLARE @Year INT=2013;
DECLARE @start DATE;
SET @start = DATEADD(YEAR, @Year-1900, 0);
SET DATEFIRST 6; -- Set start of week as Saturday
WITH n AS
(
SELECT TOP (366) -- in case of leap year
TDate = DATEADD(DAY, ROW_NUMBER() OVER (ORDER BY name)-1, @start)
FROM sys.all_objects
)
select TDate
, DATEPART(WEEK,TDate)
from n
where year(TDate) = 2013;
修改强>
因此,基于各种评论和答案,我认为这里需要的是,在给定的一天,返回同一周的所有日子,星期六作为一周的第一天。所以像这样:
set datefirst 6; -- make sure first day of week is Saturday
declare @date date = getdate(); -- change date as required here
with daysOfWeek as
(
select [date] = dateadd(dd, -datepart(dw, @date) + 1, @date)
union all
select [date] = dateadd(dd, 1, [date])
from daysOfWeek
where [date] < dateadd(dd, -datepart(dw, @date) + 7, @date)
)
select [date], dayOfWeek = datename(dw, [date])
from daysOfWeek
结果如下:
我认为这是必要的吗?
第二次修改:
首先,创建函数:
create function dbo.weekDates (@date date)
returns @dates table ([date] date, [dayofweek] varchar(9))
as
begin
with daysOfWeek as
(
select [date] = dateadd(dd, -datepart(dw, @date) + 1, @date)
union all
select [date] = dateadd(dd, 1, [date])
from daysOfWeek
where [date] < dateadd(dd, -datepart(dw, @date) + 7, @date)
)
insert into @dates ([date], [dayofweek])
select [date], [dayOfWeek] = datename(dw, [date])
from daysOfWeek;
return
end
go
使用该功能:
set datefirst 6 -- Set Saturday as first day of week
select * from dbo.weekDates (getdate()) -- Change input parameter as required
答案 1 :(得分:0)
我已经实现了显示本周的日期,但是我显示了下周的日期,我想要显示当前的周日期,此处开始日是星期六,结束日是星期五
ALTER FUNCTION GetCurrentWeek()
RETURNS @TWeek TABLE (TWeek NVARCHAR(20))
AS
BEGIN
DECLARE @Year INT= DATEPART(YEAR,GETDATE());
DECLARE @start DATE;
SET @start = DATEADD(YEAR, @Year-1900, 0);
;WITH n AS
(
SELECT TOP (366) -- in case of leap year
TDate = DATEADD(DAY, ROW_NUMBER() OVER (ORDER BY name)-1, @start)
FROM sys.all_objects
),
x AS
(
SELECT md = MIN(TDate) FROM n
WHERE DATEPART(WEEKDAY, TDate) = 7 -- assuming DATEFIRST is SATURDAY
),
y(TDate,wk) AS
(
SELECT n.TDate, ((DATEPART(DAYOFYEAR, n.TDate)
- DATEDIFF(DAY, @start, x.md)-1)/7) + 1
FROM n CROSS JOIN x
WHERE n.TDate >= x.md
AND n.TDate < DATEADD(YEAR, 1, @start)
)
INSERT @TWeek
SELECT [date] = TDate
FROM y WHERE wk =DATEPART(wk, GetDate())
ORDER BY [date];
RETURN;
END