Rish
Rish

Reputation: 457

Convert a date to a string, concatenate the string and reconvert into date in SQL

I want to convert :

select  convert(nvarchar(16), TimeLog, 120) requestTime,
        count(Request) As noOfQueries 
from    LogData 

where  TimeLog  between @StartDate and @EndDate

group by convert(nvarchar(16), TimeLog, 120) order by requestTime;

Here in the where clause the Timelog is between: 2012-06-21 and 2012-06-21 but I want it between 2012-06-21 00:00:00 and 2012-06-21 23:59:59

Hence I want to convert the @Satrtdate / @EndDate into above format so I would like to append 00:00:00 to @StartDate and 23:59:59 to @EndDate .

Upvotes: 1

Views: 418

Answers (1)

Aaron Bertrand
Aaron Bertrand

Reputation: 280252

What you want is:

SELECT 
  requestDate = CONVERT(CHAR(10), TimeLog, 120), 
  noOfQueries = COUNT(Request)
WHERE TimeLog >= @StartDate 
AND TimeLog < DATEADD(DAY, 1, @EndDate)
GROUP BY CONVERT(CHAR(10), TimeLog, 120)
ORDER BY CONVERT(CHAR(10), TimeLog, 120);

The reason you don't want to use BETWEEN is because its behavior will differ depending on the underlying data type. If it's SMALLDATETIME, you will round up, and get data from the next day. If it's DATETIME2, you could miss data between 23:59:59.0000000 and 23:59:59.9999999. And even if you know the data type now, it could change after you publish your query. Who's going to go back and correct 23:59:59 to 23:59:00 or 23:59:59.9999999? With an open-ended range, selecting everything before the next day at midnight, you'll never have to worry about it.

Please give these two articles a read:

Upvotes: 6

Related Questions