Groups | Blog | Home
all groups > sql server programming > october 2007 >

sql server programming : Dynamic Time Query


ibcarolek
10/24/2007 7:25:35 PM
I know there's someone who knows the answer to this question, but I
can't seem to figure it out - forgive me!

I want to query SQL Server and set up a query so that yesterday is
always returned.

SELECT AL1.TDate, SUM ( AL1.NBR )
FROM dbo.Table AL1
WHERE AL1.TDate = _____________?

How do I set TDate to always be yesterday?
ganesh
10/24/2007 9:25:00 PM
The below select (getdate()-1) all ways returns yesterday date

Try this

SELECT AL1.TDate, SUM ( AL1.NBR )
FROM dbo.Table AL1
WHERE AL1.TDate = select (getdate()-1)







[quoted text, click to view]
Razvan Socol
10/25/2007 1:26:12 AM
[quoted text, click to view]

To get today's date without the time, you can use:
DATEADD(d,DATEDIFF(d,0,GETDATE()),0)
or:
CONVERT(datetime,CONVERT(char(8),GETDATE(),112))

To get yesterday's date, you can substract 1 from the above expression:

SELECT AL1.TDate, SUM ( AL1.NBR )
FROM dbo.Table AL1
WHERE AL1.TDate = DATEADD(d,DATEDIFF(d,0,GETDATE()),-1)

Note: I was assuming that you are storing only the date in the TDate
column. If you are storing the date and time in this column, you can
use something like this:

SELECT AL1.TDate, SUM ( AL1.NBR )
FROM dbo.Table AL1
WHERE AL1.TDate >= DATEADD(d,DATEDIFF(d,0,GETDATE()),-1)
AND AL1.TDate < DATEADD(d,DATEDIFF(d,0,GETDATE()),0)

See also: http://www.karaszi.com/SQLServer/info_datetime.asp

--
Razvan Socol
ibcarolek
10/25/2007 7:50:40 AM
[quoted text, click to view]

Razvan, you're my hero! Thank you!! Thank you too, Ganesh. However,
only Razvan's code work. I got a syntax error using "select".
AddThis Social Bookmark Button