来自星期数和日的日期在Sql Server 2012中

时间:2014-02-22 06:01:41

标签: sql-server sql-server-2012

我有一周的天数以及一年中的周数。如何在sql中计算当天的日期。例如。2014年2月22日的天数是第7天,是第8周现在。现在怎样才能从这些信息中计算出日期。紧急。请帮忙。我想查询。

2 个答案:

答案 0 :(得分:1)

试试这个

  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

答案 1 :(得分:1)

这是我的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

你可以打电话给这个

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