Skip to content
Advertisement

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?

Advertisement

Answer

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?

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement