返回一个月内的周开始结束列表
--返回一个月内的周开始结束列表
--可跨月、跨年
--调用前请设置:SET DATEFIRST 1
ALTER FUNCTION [dbo].[GetWeekListInMonth]
(
@dtBegin DATETIME,
@dtEnd DATETIME
)
RETURNS @StructTable TABLE
(dtBeginDate DATETIME, dtEndDate DATETIME)
AS
BEGIN
IF ABS(DATEDIFF(yy, @dtBegin, @dtEnd)) > 0
RETURN
INSERT @StructTable
SELECT MIN(dd.strDate) dtBegin,
MAX(dd.strDate) dtEnd
FROM DimDate dd
WHERE dd.dtDateTime BETWEEN DATEADD(dd, DATEPART(weekday, @dtBegin) -7, @dtBegin)
AND DATEADD(dd, 7 -DATEPART(weekday, @dtEnd), @dtEnd)
GROUP BY
DATEPART(week, dd.dtDateTime)
HAVING MIN(DATEPART(weekday, dd.strDate)) = 1
AND MAX(DATEPART(weekday, dd.strDate)) = 7
UNION
SELECT MIN(dd.strDate) dtBegin,
MAX(dd.strDate) dtEnd
FROM (
SELECT *
FROM DimDate dd
WHERE dd.dtDateTime BETWEEN DATEADD(dd, -DATEPART(weekday, @dtBegin)+1, @dtBegin)
AND DATEADD(dd, 7 -DATEPART(weekday, @dtBegin), @dtBegin)
) dd
UNION
SELECT MIN(dd.strDate) dtBegin,
MAX(dd.strDate) dtEnd
FROM (
SELECT *
FROM DimDate dd
WHERE dd.dtDateTime BETWEEN DATEADD(dd, -DATEPART(weekday, @dtEnd) + 1, @dtEnd)
AND DATEADD(dd, 7 -DATEPART(weekday, @dtEnd), @dtEnd)
) dd
RETURN
END