Sql query to generate monthly pay dates within a date range

时间:2016-11-09 05:48:45

标签: sql asp.net sql-server date sql-server-2012

I want to generate monthly pay dates based on a given date and date range.Suppose I have selected "01/30/2016" as a starting pay date and date range is the year 2016.Then the pay dates will be (total days of month -1) th of other months throughout the year 2016. I have added a screenshot for the result set for the pay date "01/30/2016". I want to know the query in SQL.

Any help will be appreciated.

enter image description here

2 个答案:

答案 0 :(得分:2)

您可以如下所示:

DECLARE @SelectedDate DATETIME = '2016.01.30'
SELECT
     DATEADD(DAY, -1 - (DAY(EOMONTH(@SelectedDate)) - DAY(@SelectedDate)),  DATEADD(MONTH, v.m, DATEFROMPARTS(YEAR(@SelectedDate), 1, 1)))   
FROM
    (VALUES (1), (2), (3), (4), (5), (6), (7), (8), (9), (10), (11), (12)) AS v(m)

在月底之前剩下多少天。发现的天数将从其他月份中删除。

DAY(EOMONTH(@SelectedDate)(31) - DAY(@SelectedDate)(30)= left days ...(1)

结果:

2016-01-30
2016-02-28
2016-03-30
2016-04-29
2016-05-30
2016-06-29
2016-07-30
2016-08-30
2016-09-29
2016-10-30
2016-11-29
2016-12-30

答案 1 :(得分:0)

DECLARE @StartDate VARCHAR(10) = '01/30/2016',
        @EndDate   VARCHAR(10)='12/30/2016';

WITH _CTEDate( _date, _NextMonth)
     AS (SELECT CONVERT(DATE, @StartDate, 101),
                Eomonth(@StartDate, 1)
         UNION ALL
         SELECT Dateadd(DAY, -1, _NextMonth),
                Eomonth(Dateadd(M, 1, _date), 1)
         FROM   _CTEDate
         WHERE  _date < CONVERT(DATETIME, @EndDate, 101))
SELECT Datename(DW, _date)               [WeekDay],
       Cast(Day(_date) AS VARCHAR(2)) + ' '
       + Datename(MONTH, _date) + ' ' + ' '
       + Cast(Year(_date) AS VARCHAR(4)) AS [Date]
FROM   _CTEDate