SQL:所选日期超出范围

时间:2013-03-01 09:07:49

标签: sql sql-server sql-server-2008

我有一个查询,它返回创建行的最新日期。日期是'2010-02-03'

SELECT * FROM
[LinkedServer].[Server].[Table]
WHERE [TimeStamp]= (SELECT MAX(TimeStamp)
FROM [LinkedServer].[Server].[Table]
WHERE UserName IN 
(SELECT Tagname COLLATE DATABASE_DEFAULT FROM LocalServer.MyDatabase.dbo."Taglist"
WHERE LOCATION = 'Europe' AND COUNTRY = 'England'))

这个查询工作正常,但我想插入一个IF ELSE语句,所以如果我选择一个不同的日期,大于MAX(TimeStamp)然后返回一条错误信息。我尝试的方式如下:

IF MAX(TimeStamp) > '2011-02-15'
BEGIN

SELECT * FROM
[LinkedServer].[Server].[Table]
WHERE [TimeStamp]= (SELECT MAX(TimeStamp)
FROM [LinkedServer].[Server].[Table]
WHERE UserName IN 
(SELECT Tagname COLLATE DATABASE_DEFAULT FROM LocalServer.MyDatabase.dbo."Taglist"
WHERE LOCATION = 'Europe' AND COUNTRY = 'England'))

END
ELSE 
PRINT 'Date out of range'

不幸的是这种方式查询无效。关于我应该在哪里更改代码的任何建议? 谢谢!

1 个答案:

答案 0 :(得分:1)

Declare @MaxTS datetime

SELECT @MaxTS=MAX(TimeStamp)
FROM [LinkedServer].[Server].[Table]
WHERE UserName IN 
(SELECT Tagname COLLATE DATABASE_DEFAULT FROM LocalServer.MyDatabase.dbo."Taglist"
WHERE LOCATION = 'Europe' AND COUNTRY = 'England')

IF @MaxTS > '20110215'
BEGIN

SELECT * FROM
[LinkedServer].[Server].[Table]
WHERE [TimeStamp]= @MaxTS

END
ELSE 
PRINT 'Date out of range'