8

I have tried solution for this is like.

select dateadd(wk, datediff(wk, 0, getdate()), 0)as StartDate ,
   (select dateadd(wk, datediff(wk, 0, getdate()), 0) + 5) as EndDate

it gives monday-saturday in result, but on Sunday it gives me next week days

I want sunday as last day of week and Monday as First Day of week..

Please Help...

4

5 回答 5

12

通常,用于SET DATEFIRST 1指定星期一是一周的第一天。但是,这并不能解决这里的问题。请改用此语法:

SELECT DATEADD(week, DATEDIFF(day, 0, getdate())/7, 0) AS StartWeek,
       DATEADD(week, DATEDIFF(day, 0, getdate())/7, 5) AS EndWeek

Demo

SET DATEFIRST (Transact-SQL)

1    Monday
2    Tuesday
3    Wednesday
4    Thursday
5    Friday
6    Saturday
7    (default, U.S. English) Sunday
于 2013-10-08T07:13:52.160 回答
1

您只需添加 6 天而不是 5 天。

select dateadd(wk, datediff(wk, 0, getdate()), 0) as StartDate 
select dateadd(wk, datediff(wk, 0, getdate()), 0) + 6) as EndDate
于 2013-11-18T04:34:49.110 回答
0

这可能过于复杂,但很有趣。

--这第一部分是获取最近发生的星期一。

-- 它首先创建一个表,该表将保存所有日期直到最近的星期一,然后将该表的最小值设置为@mondaythisweek 变量。

declare @dateholder table (
    thedate date,
    theday varchar(10)
    )

declare @now datetime
set @now = GETDATE()

;with mycte as (
    select
        cast(@now as date) as "thedate",
        DATENAME(dw,@now) as "theday"
    union all
    select 
        cast(DATEADD(d,-1,"thedate") as date) as "thedate",
        DATENAME(DW,DATEADD(d,-1,"thedate")) as "theday"
    from
        mycte
    where
        "theday" <> 'Monday'
    )
insert into @dateholder
select * from mycte 
option (maxrecursion 10)

declare @mondaythisweek date
set @mondaythisweek  = (
select min(thedate)
from @dateholder
)

-- 这部分创建了一个从@mondaythisweek 到下周日的表格

;with mon_to_sun as (
    select
        @mondaythisweek as "dates",
        DATENAME(dw,@mondaythisweek) as "theday"
    union all 
    select
        cast(DATEADD(d,1,"dates") as date) as "dates",
        DATENAME(dw,cast(DATEADD(d,1,"dates") as date)) as "theday"
    from mon_to_sun
    where "theday" <> 'Sunday'
)
select * 
from mon_to_sun 
option(maxrecursion 10)
于 2014-08-06T18:42:07.523 回答
0
DECLARE
    @d datetime,
    @f datetime;

SET @d = dateadd(week,datediff(week,0,getdate())-48,0) --start of week from a year ago
SET @f = dateadd(week,datediff(week,0,getdate()),0) --start of current partial week;

create table #weeks (
    week_starting datetime primary key
)

while @d < @f
begin
    insert into #weeks (week_starting) values (@d)
    set @d = dateadd(week,1,@d)
end
select * from #weeks

drop table #weeks
于 2014-07-22T14:45:58.380 回答
0
SELECT DATEADD(week, DATEDIFF(day, 0, GETDATE())/7, 0) AS 'StartWeek(Monday)',
       DATEADD(week, DATEDIFF(day, 0, GETDATE())/7, 6) AS 'EndWeek(Sunday)'

随着时间的推移

SELECT DATEADD(week, DATEDIFF(day, 0, GETDATE())/7, 0) AS 'StartWeek(Monday)',
       DATEADD(DAY,DATEDIFF(day, 0, DATEADD(week, DATEDIFF(day, 0, GETDATE())/7, 6)), '23:59:59') AS 'EndWeek(Sunday)'
于 2019-10-06T11:54:26.430 回答