简体   繁体   中英

Get first date of each month SQL Server 2008 R2

I need to generate first date of each month starting 01/01/2000 to 12/31/2099.

Issue: Below query works in Management Studio. However, it doesn't work in SSRS. Unfortunately, I cannot create a function or a view because I do not have access to do so.

Is there an alternative way to write this query that would work with SSRS? SSRS does not like use of "TOP" in my query.

Error related to "TOP": A TOP or FETCH clause contains an invalid value.

declare @pStartDate date = '01/01/2000'
declare @pEndDate date   = '12/31/2099'

;With months(DATE, MONTH, YEAR)
as(
    SELECT TOP (DATEDIFF(MONTH, @pStartDate, @pEndDate)+1) 
        TheDate  = DATEADD(MONTH, number, @pStartDate),
        TheMonth = MONTH(DATEADD(MONTH, number, @pStartDate)),
        TheYear  = YEAR(DATEADD(MONTH, number, @pStartDate))
    FROM [master].dbo.spt_values 
    WHERE [type] = N'P' ORDER BY number
)
select cast(DATE as Date) as Date from months

I just rearranged your code in a simpler and efficient way, without TOP clause:

declare @pStartDate date = '01/01/2000'
declare @pEndDate date   = '12/31/2099'    

SELECT DATEADD(MONTH, number, @pStartDate) as Date 
FROM [master].dbo.spt_values 
  WHERE [type] = N'P' 
  AND number < DATEDIFF(MONTH, @pStartDate, @pEndDate)+1
  ORDER BY number 

When you add one month to a date it keeps the day. Day 30 and 31 are special cases, try it yourself.

Try this simple, recursive CTE to get what you want:

declare @pStartDate date = '01/01/2000'
declare @pEndDate date   = '12/31/2099'

;with FirstDayOfMonth as(
    select @pStartDate as [firstDayOfMonth]
    union all
    select DATEADD(month, 1, [firstDayOfMonth]) from FirstDayOfMonth
    where DATEADD(month, 1, [firstDayOfMonth]) < @pEndDate
)

select * from FirstDayOfMonth
option (maxrecursion 0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM