WHERE子句中的CASE - 传递多个值

时间:2018-05-21 07:07:23

标签: sql sql-server

我需要在子句

中传递多个案例
SELECT *
FROM [dbname].[dbo].[tablename] CD, 
     [dbname].[dbo].Applications_N_Device_Master ADM
WHERE 
    CD.Product_ID = ADM.Product_ID
    AND CD.Reg_Date BETWEEN @FromDate AND @ToDate
    AND CD.CompType_ID = '2' 
    AND cd.closed IN (CASE 
                         WHEN @Status = 'yes' OR 'NO' 
                            THEN @status
                            ELSE 'YES', 'NO'
                      END)
ORDER BY 
    CD.Comp_ID DESC

我在else 'YES','NO'部分

上收到错误消息

2 个答案:

答案 0 :(得分:2)

SELECT *
FROM [dbname].[dbo].[tablename] CD,  
     [dbname].[dbo].Applications_N_Device_Master ADM
WHERE CD.Product_ID = ADM.Product_ID 
  AND CD.Reg_Date BETWEEN @FromDate AND @ToDate 
  AND CD.CompType_ID='2' 
  AND (
        (@status IN ('yes', 'NO') AND cd.closed = @status) OR
        (@status NOT IN ('yes', 'NO') AND cd.closed IN ('YES', 'NO'))
      )
ORDER BY 
    CD.Comp_ID DESC

您可能希望ISNULL使用@status来处理空值。

答案 1 :(得分:0)

SELECT * FROM [dbname].[dbo].[tablename] CD, 
              [dbname].[dbo].Applications_N_Device_Master ADM 
WHERE CD.Product_ID = ADM.Product_ID 
  AND CD.Reg_Date BETWEEN @FromDate AND @ToDate 
  AND CD.CompType_ID='2' 
  AND cd.closed in (CASE WHEN @Status='yes'THEN 
                         WHEN @Status='no' THEN @status 
                         ELSE 'YOURELSEPART' END) 
ORDER BY CD.Comp_ID DESC

我认为这将解决您的问题