在SQL Server中按日期获取星期几(需要类似于C#函数的T-SQL函数)

时间:2015-10-20 07:52:16

标签: c# sql-server-2008

我一直使用C#函数来获取星期几,我需要在T-SQL中使用类似的函数来获得相同的结果。

public static int GetWeekNumberOfMonth(DateTime date)
{
    date = date.Date;

    DateTime firstMonthDay = new DateTime(date.Year, date.Month, 1);

    var mon = (int)DayOfWeek.Monday;
    var dofw = (int)firstMonthDay.DayOfWeek;

    DateTime firstMonthMonday = firstMonthDay.AddDays((DayOfWeek.Monday + 7 - firstMonthDay.DayOfWeek) % 7);

    if (firstMonthMonday > date)
    {
        firstMonthDay = firstMonthDay.AddMonths(-1);
        firstMonthMonday = firstMonthDay.AddDays((DayOfWeek.Monday + 7 - firstMonthDay.DayOfWeek) % 7);
    }

    return (date - firstMonthMonday).Days / 7 + 1;
}

1 个答案:

答案 0 :(得分:0)

试试这样:

DECLARE @d DATETIME
SET @d = '2015-10-20'

SELECT DATEPART(WEEK, @d)  -
    DATEPART(WEEK, DATEADD(MM, DATEDIFF(MM,0,@d), 0))+ 1 AS WEEK_OF_MONTH