SQL如果在Where子句中有其他

时间:2014-07-22 20:18:42

标签: sql sql-server sql-server-2005

这是我的查询,现在我收到错误

  

关键字' ELSE'

附近的语法不正确

在SQL Server 2005上。

DECLARE @addHours INT, @bufferTime INT, @timeNow SMALLDATETIME,
        @lookAhead SMALLDATETIME, @todayIs SMALLDATETIME, @getWhat VARCHAR(20)

SET @addHours = 3
SET @bufferTime = 10
SET @timeNow = (SELECT CONVERT(VARCHAR(8),GETDATE(),108))
SET @lookAhead = DATEADD(hh, @addHours, @timeNow) --Add Look Ahead Hours
SET @lookAhead = DATEADD(mi, @bufferTime, @lookAhead) --Add buffer minutes
SET @todayIs = (SELECT(CONVERT(VARCHAR(10),GETDATE(),101)))
SET @getWhat = 'UpComing'

SELECT 
    RR.Emp_ID, RR.RoomName, RR.mtgName, RR.mtgTime, RR.mtgEnd, @timeNow, @lookAhead 
FROM 
    ABC.RoomReservations RR 
LEFT JOIN 
    ABC.Rooms R ON RR.RoomName = R.RoomName
WHERE 
    RR.Active = 'Y' 
    AND RR.mtgDate = @todayIs
    AND RR.Room = 'Y' 
    AND R.Viewable = 'Y'

IF @getWhat ='UpComing'
    AND RR.mtgTime >= @timeNow AND RR.mtgTime <= @lookAhead 
ELSE
    AND RR.mtgTime <= @timeNow
END

AND RR.mtgEnd >= @timeNow
ORDER BY RR.RoomName, RR.mtgTime

我尝试做的是@getWhat = 'UpComing',然后我希望上面的查询有RR.mtgTime >= @timeNow AND RR.mtgTime <= @lookAhead条件,如果@getWhat = 'HappeningNow'那么我想要RR.mtgTime >= @timeNow AND RR.mtgTime <= @lookAhead条件WHERE条款。

我一定是做错了所以非常感谢任何帮助。

1 个答案:

答案 0 :(得分:3)

将其更改为:

WHERE RR.Active='Y' AND RR.mtgDate= @todayIs
  AND RR.Room='Y' AND R.Viewable = 'Y'
  AND ((@getWhat ='UpComing' AND RR.mtgTime >= @timeNow AND RR.mtgTime <= @lookAhead )
   OR (RR.mtgTime <= @timeNow))