Sql获取月份表中两个日期之间的名称

时间:2014-06-09 09:20:42

标签: sql sql-server

我的表格中有ID , startDate , EndDate

我需要以这种方式对表格的每一行使用:

没有具体的值,如:

declare @start DATE = '2011-05-30'
declare @end DATE = '2011-06-10' 

;with months (date)
AS
(
        SELECT @start
        UNION ALL
        SELECT DATEADD(month,1,date)
        from months
        where DATEADD(month,1,date)<= DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@end)+1,0))
)
select Datename(month,date) from months

有可能吗?

1 个答案:

答案 0 :(得分:0)

如果我找到你,你可能看起来像:

DECLARE @tbl TABLE (id int, start date, finish date)
INSERT INTO @tbl VALUES
(1, '2011-05-30', '2011-06-10'),
(2, '2011-08-14', '2011-08-29'),
(3, '2012-01-01', '2012-09-15')

;WITH periods
AS(
    SELECT
        id, start, finish
    FROM
        @tbl
)
,months(id, date)
AS
(
        SELECT
            id,
            start
        FROM
            @tbl
        UNION ALL SELECT
            tbl.id,
            DATEADD(month,1,months.date)
        FROM
            months
            inner join @tbl as tbl on tbl.id = months.id
        WHERE
            DATEADD(month,1,months.date)<= DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,finish)+1,0))
)
SELECT
    id,
    Datename(month,date)
FROM
    months
ORDER BY
    id

如果你需要连接几个月&#39;名称,你可以用smth替换最后的SELECT,如下所示:

SELECT
    id,
    (
        SELECT
            Datename(month,date) + ' ' as 'text()'
        FROM
            months as i
        WHERE
            i.id = o.id
        FOR
            XML PATH('')
    )
FROM
    months AS o
GROUP BY
    o.id