0

我正在尝试将IF.. ELSEinWHERE子句如下所示,但收到错误消息

“关键字 '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
  )
4

2 回答 2

4

您不能IF以这种方式使用内部子选择。相反,使用 an来测试子句AND中变量的值@categoryIDWHERE这将需要两个()组之间具有逻辑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
))
于 2012-05-31T19:01:22.837 回答
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))
于 2012-05-31T19:02:50.637 回答