我一直使用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;
}
答案 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