小编典典

SQL如何正确设置和使用日期变量值?

sql

我有以下查询,该查询使用日期变量,该变量在存储过程内部生成:

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))

问题是@sp_Date值似乎被忽略了,我想知道为什么吗?我定义或使用不正确吗?


阅读 216

收藏
2021-04-07

共1个答案

小编典典

您的语法很好,它将返回LastAdDate过去6个月内的行;

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

您确定LastAdDate类型DATETIME吗?

2021-04-07