How to retrieve all inserted rows during a given month using T-Sql
-
11-09-2019 - |
Question
I'm trying to retrieve all rows inserted during a specific month.
SELECT
dbo.Post.UserId,
dbo.Post.Tags,
dbo.Post.CommentCount,
dbo.Post.Status,
dbo.Post.PostDate,
dbo.Post.[Content],
dbo.Post.Title,
dbo.Post.PostId,
dbo.[User].DisplayName
FROM
dbo.Post INNER JOIN
dbo.[User] ON dbo.Post.UserId = dbo.[User].UserId
Where PostDate >= DATEADD(mm, 0, DATEDIFF(mm, 0, '01/28/2009'))
AND PostDate <= DATEADD(mm, 0, DATEDIFF(mm, 0, '01/28/2009'))
Any idea's?
Solution
WHERE PostDate >= DATEADD(mm, DATEDIFF(mm, 0, '01/28/2009'), 0)
AND PostDate < DATEADD(mm, 1 + DATEDIFF(mm, 0, '01/28/2009'), 0)
OTHER TIPS
You mention for a "given month", I'm assuming a month number from 1 to 12. If you start with a date and just want everything that falls within that month:
@month = datepart(mm, 'given date');
@year = datepart(yy, 'given date');
Then use:
Where
datepart(mm, Post.Postdate) = @month
and datepart(yy, Post.PostDate) = @year
like that.
(I added the year in case you care about that. :-))
You want to create the starting moment of that month and the starting moment of the next month, then take the dates from and including the starting moment, and until but not including the next starting moment.
I.e. the result should be equivalent to:
Where PostDate >= '01/01/2009' and PostDate < '02/01/2009'
This will get you exactly that month and no overlapping onto the next month.
The expression DATEDIFF(mm, 0, '2009-01-28')
will give you the number of months from 01/01/1900
, so you should use that date as the third parameter in the DATEADD
:
DATEADD(mm, DATEDIFF(mm, 0, '01/28/2009'), '01/01/1900')
To get the starting moment of the next month you just use '02/01/1900'
as offset. Let's put that in the condition:
Where
PostDate >= DATEADD(mm, DATEDIFF(mm, 0, '01/28/2009'), '01/01/1900') and
PostDate < DATEADD(mm, DATEDIFF(mm, 0, '01/28/2009'), '02/01/1900')
This will do it.
Where PostDate >= DATEADD(mm, DATEDIFF(mm, 0, '01/28/2009'), 0)
AND PostDate < DATEADD(mm, DATEDIFF(mm, 0, '01/28/2009') + 1, 0)
Also, I usually set up my date range before the query so I don't have to put date functions in the where clause.
declare @from datetime;
declare @thru datetime;
set @from = DATEADD(mm, DATEDIFF(mm, 0, '01/28/2009'), 0);
set @thru = DATEADD(mm, 1, @from);
...
Where PostDate >= @from
AND PostDate < @thru
@dtInput = '01/28/2009'
-- subtract current days (less one) to get to start of month
set @dtStart = dateadd( dd, 1 - datepart( dd, @dtInput ), @dtInput )
-- add a month, then subtract 1 sec to get 23:59:59 on last day of month
set @dtEnd = dateadd( ss, -1, dateadd( mm, 1, @dtStart ))
SELECT ... WHERE PostDate between @dtStart and @dtEnd