我有以下查询使用日期变量,该变量在存储过程中生成:
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值似乎被忽略了,我想知道为什么?我是否错误地定义或使用了它?
sql microsoft sql-server-2008
用户错误...
谢谢,R。
答案 0 :(得分:18)
您的语法很好,它将返回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
吗?
答案 1 :(得分:2)
如果您使用静态日期值手动写出查询(例如'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 > '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))