Date From Week Number and Day In Sql Server 2012

痴心易碎 提交于 2021-02-19 02:57:12

问题


I have day number of the week as well as week number of the year .How can i calculate date of that day in sql .For Example.the day number of 22-Feb-2014 is 7th and it is 8th week of the year.Now how can i calculate the date back from this information.Its urgent.Please help.I want query.


回答1:


Here is my verison

create FUNCTION date_from_week_number_day 
(
     @year int = 2014
    ,@weeknumber int = 8 
    ,@day int = 7


)
RETURNS date
AS
BEGIN


    declare
         @date date
        ,@first_date_of_year date


set @first_date_of_year = CONVERT(date,cast(@year as varchar(4))+'.1.1') --First calculate first day of year


set @date =    dateadd(dd,@day -- we add days acoring of day of week
                        ,dateadd(dd,-1*DATEPART(WEEKDAY,@first_date_of_year) --first day of year is not first day of week so we go back days how day has pass
                            , DATEADD(WEEK,@weeknumber-1,@first_date_of_year) --1. we go to week before last
                            )
                        )

return @date

END

you can call this

SET DATEFIRST  7
select dbo.date_from_week_number_day(2014,8,7)



回答2:


Try this

  CREATE FUNCTION dbo.Date_From_WN_DN (@YearNum int,@WeekNum int,@DayNum int)
        RETURNS Date AS
    BEGIN
        DECLARE @FirstDayYear As Date;
        SET @FirstDayYear='01/01/' + CAST(@YearNum As varchar)
        RETURN dateadd(d,((@DayNum)-datepart(weekday,@FirstDayYear)),dateadd(week, @WeekNum-1,@FirstDayYear))
    END


    SET DATEFIRST 7
    SELECT dbo.DEV_VW_WeekSerial (2014,8,7)

O/P :

enter image description here



来源:https://stackoverflow.com/questions/21950427/date-from-week-number-and-day-in-sql-server-2012

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!