如何在where where condition SQL中插入

时间:2014-11-27 16:11:13

标签: sql tsql where-clause

我有这个查询,

SELECT [Equipment]
      ,[CounterType]      
      ,SUM([Quantity])
FROM [FlexNet].[dbo].[AT_MACHINE_COUNTER]
WHERE 
    CreatedOn IS NOT NULL
    AND [FlexNet].[dbo].AF_GetUTCToLocal(CreatedOn) between @DATA_START and @DATA_END
    AND [Equipment] LIKE @MACHINE
    AND CounterType IN 
    (CASE WHEN @MACHINE LIKE 'PACKER001' THEN 2 END)

我想在WHERE条件中插入此IF:

IF @MACHINE LIKE 'PACKER001' THEN CounterType = 1
ELSE 'I don't want apply any condition'

所以查询应该类似于此(但我知道找不到此查询):

    SELECT [Equipment]
          ,[CounterType]      
          ,SUM([Quantity])
    FROM [FlexNet].[dbo].[AT_MACHINE_COUNTER]
    WHERE 
        CreatedOn IS NOT NULL
        AND [FlexNet].[dbo].AF_GetUTCToLocal(CreatedOn) between @DATA_START and @DATA_END
        AND [Equipment] LIKE @MACHINE
                    IF @MACHINE LIKE 'PACKER001' THEN 
                       AND CounterType =2
                    END IF

我们可以帮助我吗? reguars

2 个答案:

答案 0 :(得分:3)

您可以通过将两个“分支”与OR子句组合来构建条件where子句,如同此示例一样,但请注意,这充满了性能和可维护性挑战:

SELECT [Equipment]
      ,[CounterType]      
      ,SUM([Quantity])
FROM [FlexNet].[dbo].[AT_MACHINE_COUNTER]
WHERE 
    CreatedOn IS NOT NULL
    AND [FlexNet].[dbo].AF_GetUTCToLocal(CreatedOn) between @DATA_START and @DATA_END
    AND [Equipment] LIKE @MACHINE
    AND (@MACHINE = 'PACKER001' AND CounterType IN (2)
         OR @MACHINE <> 'PACKER001')

作为在Sql中执行此操作的替代方法,我通常会尝试在应用程序层中对数据进行此类动态过滤,例如: LINQ的功能,例如使用IQueryable来有条件地组合过滤器,或者优秀PredicateBuilder这样做更容易。

答案 1 :(得分:3)

你的第一次尝试几乎就在那里。只需在Else中添加Case Statement部分即可解决CounterType问题。

SELECT [Equipment],
       [CounterType],
       Sum([Quantity])
FROM   [FlexNet].[dbo].[AT_MACHINE_COUNTER]
WHERE  CreatedOn IS NOT NULL
       AND [FlexNet].[dbo].Af_getutctolocal(CreatedOn) BETWEEN @DATA_START AND @DATA_END
       AND [Equipment] LIKE @MACHINE
       AND CounterType = CASE
                           WHEN @MACHINE LIKE 'PACKER001' THEN 2
                           ELSE CounterType
                         END