1

我有一个查询,它返回创建行的最新日期。日期是'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'

不幸的是,这样查询不起作用。关于我应该在哪里更改代码的任何建议?谢谢!

4

1 回答 1

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'
于 2013-03-01T09:13:02.310 回答