SQL Server: How to select rows that were inserted on the same day?
-
28-10-2019 - |
Вопрос
I have a loop, that goes through some entries. In the loop I'm getting creation date and I need to find if there were entries inserted on the same day. So for example if creation date = 2011-08-31 21:19:14.345
, I need to select all rows where the creation date is between 2011-08-31 00:00:00.000
and 2011-08-31 23:59:59.999
How do I do this with SQL?
Решение
Without any other schema details, and if this is SQL Server 2K8+, you could do this:
DECLARE @CreationDate Date = '2011-08-31';
SELECT *
FROM SomeTable
WHERE CONVERT(Date, CreationDate) = @CreationDate;
By converting to a date
instead of working with datetime
you lose the time component and "normalize" how you're comparing the values.
Another way to lose the time component for comparison purposes is:
DECLARE @CreationDate DateTime;
SELECT @CreationDate = '2011-08-31 21:19:14.345';
SELECT @CreationDate; -- 2011-08-31 21:19:14.345
SELECT @CreationDate = CONVERT(DateTime, FLOOR(CONVERT(Float, @CreationDate)));
SELECT @CreationDate; -- 2011-08-31 00:00:00.000
You would use that if you don't have the date
data type.
Другие советы
In order to catch all the times in that day do this:
SELECT * FROM MyTable
WHERE DateCreated >= @TheDate AND DateCreated < DATEADD(day, 1, @TheDate)
Where @TheDate
must be the pure date without time. It works even when DateCreated
has a time part very close to midnight.
You can try this:
SELECT * FROM SomeTable
WHERE
DAY(TDATE) = DAY(CreationDate)
AND
MONTH(TDATE) = MONTH(CreationDate)
AND
YEAR(TDATE) = YEAR(CreationDate)