如何从tsql

时间:2016-12-14 16:03:47

标签: sql-server tsql

有人可以根据201648这样的周年整数来帮助我获取一周的第一天和最后一天,而无需设置@@firstdate属性。我希望iso datedatetime格式在星期一开始。{/ p>

2 个答案:

答案 0 :(得分:1)

经过一番考虑之后,我想也许我的动态日期/时间范围UDF可能在这里有所帮助。我使用此UDF生成动态日期/时间范围。您可以提供所需的日期范围,日期部分和增量。理货表也可以做到这一点

在这种情况下,我们按照要求获得第N个星期一,而不管日期部分(WK,..)。

Declare @YYYYWW int = 201648

Select WkNbr = B.RetSeq 
      ,WkBeg = B.RetVal
      ,WkEnd = DateAdd(DD,6,B.RetVal)
 From  (
        Select MinDate=Min(RetVal) 
         From  [dbo].[udf-Range-Date](DateFromParts(Left(@YYYYWW,4),1,1),DateFromParts(Left(@YYYYWW,4),1,10),'DD',1) 
         Where DateName(DW,RetVal)='Monday'
       ) A
 Cross Apply (Select * From [dbo].[udf-Range-Date](A.MinDate,DateFromParts(Left(@YYYYWW,4),12,31),'DD',7) ) B
 Where B.RetSeq = Right(@YYYYWW,2)

返回

WkNbr   WkBeg         WkEnd
48      2016-11-28    2016-12-04

UDF如有兴趣

CREATE FUNCTION [dbo].[udf-Range-Date] (@R1 datetime,@R2 datetime,@Part varchar(10),@Incr int)
Returns Table
Return (
    with cte0(M)   As (Select 1+Case @Part When 'YY' then DateDiff(YY,@R1,@R2)/@Incr When 'QQ' then DateDiff(QQ,@R1,@R2)/@Incr When 'MM' then DateDiff(MM,@R1,@R2)/@Incr When 'WK' then DateDiff(WK,@R1,@R2)/@Incr When 'DD' then DateDiff(DD,@R1,@R2)/@Incr When 'HH' then DateDiff(HH,@R1,@R2)/@Incr When 'MI' then DateDiff(MI,@R1,@R2)/@Incr When 'SS' then DateDiff(SS,@R1,@R2)/@Incr End),
         cte1(N)   As (Select 1 From (Values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) N(N)),
         cte2(N)   As (Select Top (Select M from cte0) Row_Number() over (Order By (Select NULL)) From cte1 a, cte1 b, cte1 c, cte1 d, cte1 e, cte1 f, cte1 g, cte1 h ),
         cte3(N,D) As (Select 0,@R1 Union All Select N,Case @Part When 'YY' then DateAdd(YY, N*@Incr, @R1) When 'QQ' then DateAdd(QQ, N*@Incr, @R1) When 'MM' then DateAdd(MM, N*@Incr, @R1) When 'WK' then DateAdd(WK, N*@Incr, @R1) When 'DD' then DateAdd(DD, N*@Incr, @R1) When 'HH' then DateAdd(HH, N*@Incr, @R1) When 'MI' then DateAdd(MI, N*@Incr, @R1) When 'SS' then DateAdd(SS, N*@Incr, @R1) End From cte2 )

    Select RetSeq = N+1
          ,RetVal = D 
     From  cte3,cte0 
     Where D<=@R2
)
/*
Max 100 million observations -- Date Parts YY QQ MM WK DD HH MI SS
Syntax:
Select * from [dbo].[udf-Range-Date]('2016-10-01','2020-10-01','YY',1) 
Select * from [dbo].[udf-Range-Date]('2016-01-01','2017-01-01','MM',1) 
*/

答案 1 :(得分:1)

declare @yrwk int = 201648 
declare @yr int = left(@yrwk,4)
declare @wk int = right(@yrwk,2)

select dateadd (week, @wk, dateadd (year, @yr-1900, 0)) - 4 - datepart(dw, dateadd (week, @wk, dateadd (year, @yr-1900, 0)) - 4) + 1

--returns 11/27/2016 which is Sunday of that week (start of week)
--change +1 to +2 at the end for "Monday"