• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 462
  • Last Modified:

sql getDate not working

Hi

I have the following SQL
 Select ID from UsageLogs where BranchId = 51 AND MachineId = 133 AND ReportedDate = GETUTCDATE()

Open in new window

I have also tried GetDate()
but i get 0 results
even though i know there is a record in table with the right info

The date is stored as

2014-02-25 17:21:03.8530000
I'm not bothered about time, i just want to match the date

any ideas?
0
websss
Asked:
websss
1 Solution
 
David KrollCommented:
Select ID from UsageLogs where BranchId = 51 AND MachineId = 133 AND CONVERT(varchar, ReportedDate, 101) = CONVERT(VARCHAR, GetDate(),101)
0
 
Patrick MatthewsCommented:
This will be a little more index-friendly:

DECLARE @StartDate datetime, @EndDate datetime

SET @StartDate = DATEADD(day, 0, DATEDIFF(day, 0, GETDATE()))
SET @EndDate = DATEADD(day, 1, @StartDate)

Select ID 
from UsageLogs 
where BranchId = 51 AND MachineId = 133 AND 
    ReportedDate >= @StartDate AND ReportedDate < @EndDate

Open in new window

0
 
Kevin CrossChief Technology OfficerCommented:
I would avoid converting your column to character strings.  I would leave your dates as dates.  Instead use ranges.
SELECT ID 
FROM UsageLogs 
WHERE BranchId = 51 AND MachineId = 133 
AND ReportedDate >= DATEADD(DD, DATEDIFF(DD, 0, GETUTCDATE()), 0)
AND ReportedDate < DATEADD(DD, DATEDIFF(DD, 0, GETUTCDATE())+1, 0)
;

Open in new window

This pulls every time stamp between midnight of the day you request and the next day.

If you have SQL 2008 or higher, you can use the DATE data type which has no time.

CONVERT(DATE, GETUTCDATE()) and CONVERT(DATE, DATEADD(DD, 1, GETUTCDATE())) can replace the DATEDIFF calculations.

EDIT: I just saw Patrick posted the same suggestion, so sorry for the duplication.
0
 
DBAduck - Ben MillerPrincipal ConsultantCommented:
Yes, do not use Convert in the where clause on the column in the table, you are guaranteed to have a table scan.  It is better to do a range as was illustrated.
0

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now