Where子句中的CASE语句? '>'附近的语法不正确

时间:2012-04-02 11:10:23

标签: sql-server

我正在尝试将CASE语句放在Where子句中,但我收到错误:'>'附近的语法不正确。

WHERE 
ItemCategoryID=@CategoryID 
AND AuctionStatus=1 
AND SE_UsersMain.isActive=1 
AND AuctionOwner!=@OwnerID
AND    
CASE                    
WHEN @CompareSign=1 THEN  @CurrentAmount>@FilterAmount 
WHEN @CompareSign=2 THEN @CurrentAmount<@FilterAmount 
WHEN @CompareSign=3 THEN @CurrentAmount=@FilterAmount 
END

3 个答案:

答案 0 :(得分:3)

试试这个:

WHERE ItemCategoryID      = @CategoryID
AND AuctionStatus         = 1
AND SE_UsersMain.isActive = 1
AND AuctionOwner!         = @OwnerID
AND
    CASE
      WHEN @CompareSign  = 1 AND @CurrentAmount>@FilterAmount THEN '1'
      WHEN @CompareSign  = 2 AND @CurrentAmount<@FilterAmount THEN '1'
      WHEN @CompareSign  = 3 AND @CurrentAmount=@FilterAmount THEN '1'
      ELSE '0'
    END = '1'

答案 1 :(得分:1)

CASE是一个返回单个值的表达式,而不是flow语句的控件。实现这一点的最简单方法可能是动态SQL:

DECLARE @sql NVARCHAR(MAX);
SET @sql = N'SELECT ...';

SET @sql = @sql + ' WHERE 
ItemCategoryID=$c$ 
AND AuctionStatus=1 
AND SE_UsersMain.isActive=1 
AND AuctionOwner!=$o$
AND $ca$ $sign$ $fa$;';

SET @sql = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
  '$c$', RTRIM(@CategoryID)),
  '$o$', RTRIM(@OwnerID)),
  '$ca$', RTRIM(@CurrentAmount)),
  '$sign$', CASE @CompareSign WHEN 1 THEN '>' WHEN 2 THEN '<' WHEN 3 THEN '=' END),
  '$fa$', RTRIM(@FilterAmount));

PRINT @sql;
--EXEC sp_executesql @sql;

答案 2 :(得分:0)

如果您正在编写存储过程,GavinCattell给出的解决方案似乎正在工作,但我认为因为您没有在case语句中使用任何列,那么为什么要在查询中进行此计算。您可以使用if-else语句。 在查询内部执行此操作会在很大程度上减慢查询速度,并且使用if语句会更快。