关键字'IF'附近的语法不正确

时间:2012-05-31 18:56:32

标签: sql sql-server

我正在尝试将IF .. ELSE置于WHERE子句中,如下所示,但收到错误消息

  

“关键字'IF'附近的语法不正确。'''附近的语法不正确。”

DECLARE @categoryID int

SET @categoryID = 0

SELECT * from SE_Auctions
  WHERE ItemCategoryID IN
  (
   IF @categoryID = 0
     SELECT CategoryID from SE_ItemCategory
   ELSE
     SELECT CategoryID from SE_ItemCategory 
    WHERE ParentID = @categoryID 
          OR CategoryID = @categoryID
  )

2 个答案:

答案 0 :(得分:1)

您不能以这种方式在子选择中使用IF。相反,使用AND来测试@categoryID子句中变量WHERE的值。这将需要两个()组,它们之间具有逻辑OR

WHERE 
-- First case, @categoryID = 0
(@categoryID = 0 AND ItemCategoryID IN (
  SELECT CategoryID from SE_ItemCategory
))
-- Other case, @categoryID <> 0
OR (@categoryID <> 0 AND ItemCategoryID IN (
  SELECT CategoryID from SE_ItemCategory 
    WHERE ParentID=@categoryID OR CategoryID=@categoryID
))

答案 1 :(得分:1)

您不能将if放在SQL语句的中间。有几种方法可以实现这一目标:

--Example 1
DECLARE @categoryID int = 0

SELECT * from SE_Auctions
WHERE 
ItemCategoryID IN
(SELECT CategoryID from SE_ItemCategory where @categoryID=0
union all
SELECT CategoryID from SE_ItemCategory 
    WHERE ParentID=@categoryID OR CategoryID=@categoryID) 

--Example 2
DECLARE @categoryID int = 0

SELECT * from SE_Auctions
WHERE 
(@categoryID=0
and ItemCategoryID IN
(SELECT CategoryID from SE_ItemCategory))
or (@categoryID <> 0
and ItemCategoryID IN
(SELECT CategoryID from SE_ItemCategory 
    WHERE ParentID=@categoryID OR CategoryID=@categoryID))

--Example 3
DECLARE @categoryID int = 0

SELECT * from SE_Auctions
WHERE 
ItemCategoryID IN
(SELECT CategoryID from SE_ItemCategory 
    WHERE ParentID=@categoryID OR CategoryID=@categoryID or @categoryID=0))