2

I have this query, it supposes to display data from current date (today) only

SELECT * FROM Customer WHERE visitTime <= GETDATE() AND visitTime > GETDATE() - 1

where visitTime is datetime type

But it doesn't work well because I think problem is at AND visitTime > GETDATE() - 1 but I don't know how to fix this, anybody has any suggestions?

Ronaldinho Learn Coding
  • 13,254
  • 24
  • 83
  • 110
  • possible duplicate of [Get row where datetime column = today - SQL server noob](http://stackoverflow.com/questions/2583228/get-row-where-datetime-column-today-sql-server-noob) – bummi Oct 16 '14 at 22:09

5 Answers5

7

Look at this example:

declare @visitTime datetime  ='2014-10-16 23:59:59.000'
select GETDATE() GETDATE, @visitTime visitTime, GETDATE() - 1 [GETDATE-1]

GETDATE                 visitTime               GETDATE-1
2014-10-17 00:02:18.980 2014-10-16 23:59:59.000 2014-10-16 00:02:18.980

You'll see that the visittime date clearly falls in the range you specified as the lower bound (the -1) subtracts a whole day and not just the time part.

You could use this instead:

-- using GETDATE() for the upper bound misses visitTime that are 
-- on the current day, but at a later time than now.
WHERE visitTime < DateAdd(Day, DateDiff(Day, 0, GetDate())+1, 0)
AND   visitTime >= DateAdd(Day, DateDiff(Day, 0, GetDate()), 0)

or if you're on SQL Server 2008+ that has adatedata type, this:

WHERE CAST(visitTime AS DATE) = CAST(GETDATE() AS DATE)

Note thatGETDATE()is T-SQL specific, the ANSI equivalent isCURRENT_TIMESTAMP

jpw
  • 44,361
  • 6
  • 66
  • 86
1

Assuming today is midnight last night to midnight tonight, you can use following condition

Select * from Customer where 
visitTime >=  DateAdd(d, Datediff(d,1, current_timestamp), 1)
and
visitTime < DateAdd(d, Datediff(d,0, current_timestamp), 1);
user353gre3
  • 2,747
  • 4
  • 24
  • 27
0
SELECT * FROM Customer WHERE visitTime > =  convert(date,getdate()) 
and visitTime <  dateadd(d,1,convert(date,getdate())) 
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
0

Check this out

select *
from Customers
where convert(date,createddate) = convert(date,getdate()); 
iamdave
  • 12,023
  • 3
  • 24
  • 53
0

Gets detail of to date only:
SELECT * FROM PRODUCTION WHERE CAST(CREATIONDATE AS DATE) = CAST(GETDATE() AS DATE)

Ferdipux
  • 5,116
  • 1
  • 19
  • 33