Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL How to correctly set a date variable value and use it?

I have the following query which uses a date variable, which is generated inside the stored procedure:

DECLARE @sp_Date DATETIME
SET @sp_Date = DateAdd(m, -6, GETDATE())

SELECT DISTINCT pat.PublicationID
     FROM PubAdvTransData AS pat 
     INNER JOIN PubAdvertiser AS pa ON pat.AdvTransID = pa.AdvTransID
     WHERE (pat.LastAdDate > @sp_Date) AND (pa.AdvertiserID = 12345))

The problem is that the @sp_Date value appears to be being ignored and I am wondering why? Have I defined or used it incorrectly?

like image 292
flavour404 Avatar asked Apr 29 '10 20:04

flavour404


People also ask

How do you assign a date to a variable in SQL?

SQL Date Data TypesDATE - format YYYY-MM-DD. DATETIME - format: YYYY-MM-DD HH:MI:SS. TIMESTAMP - format: YYYY-MM-DD HH:MI:SS. YEAR - format YYYY or YY.

How do you set a DateTime variable?

There are two ways to initialize the DateTime variable: DateTime DT = new DateTime();// this will initialze variable with a date(01/01/0001) and time(00:00:00). DateTime DT = new DateTime(2019,05,09,9,15,0);// this will initialize variable with a specific date(09/05/2019) and time(9:15:00).


2 Answers

Your syntax is fine, it will return rows where LastAdDate lies within the last 6 months;

select cast('01-jan-1970' as datetime) as LastAdDate into #PubAdvTransData 
    union select GETDATE()
    union select NULL
    union select '01-feb-2010'

DECLARE @sp_Date DATETIME = DateAdd(m, -6, GETDATE())

SELECT * FROM #PubAdvTransData pat
     WHERE (pat.LastAdDate > @sp_Date)

>2010-02-01 00:00:00.000
>2010-04-29 21:12:29.920

Are you sure LastAdDate is of type DATETIME?

like image 120
Alex K. Avatar answered Oct 22 '22 22:10

Alex K.


If you manually write out the query with static date values (e.g. '2009-10-29 13:13:07.440') do you get any rows?

So, you are saying that the following two queries produce correct results:

SELECT DISTINCT pat.PublicationID
FROM PubAdvTransData AS pat 
    INNER JOIN PubAdvertiser AS pa 
        ON pat.AdvTransID = pa.AdvTransID
WHERE (pat.LastAdDate > '2009-10-29 13:13:07.440') AND (pa.AdvertiserID = 12345))

DECLARE @sp_Date DATETIME
SET @sp_Date = '2009-10-29 13:13:07.440'

SELECT DISTINCT pat.PublicationID
FROM PubAdvTransData AS pat 
    INNER JOIN PubAdvertiser AS pa 
        ON pat.AdvTransID = pa.AdvTransID
WHERE (pat.LastAdDate > @sp_Date) AND (pa.AdvertiserID = 12345))
like image 32
Thomas Avatar answered Oct 22 '22 21:10

Thomas