如何在CASE中使用IN

时间:2018-04-30 06:22:15

标签: sql sql-server

SELECT T_MW.*
INTO #temp
FROM T_MWP T_MW
WHERE T_MW.CompanyID = 2
AND (
    CASE 
        WHEN @Currency IS NOT NULL
            THEN (
                    T_MW.Currency IN (
                        SELECT *
                        FROM #Currency
                        )
                    )
        END
    )
AND (
    CASE 
        WHEN @Asset IS NOT NULL
            THEN (
                    T_MW.Asset IN (
                        SELECT *
                        FROM #Asset
                        )
                    )
        END
    )

这里#Asset是一个包含资产的表,而#Currency是一个包含Currency的临时表。使用以下查询

创建#Asset和#Currency
SELECT *
INTO #Asset
FROM dbo.Split(@Asset, ',');

2 个答案:

答案 0 :(得分:3)

使用OR代替案例

SELECT 
T_MW.*
INTO #temp
FROM T_MWP T_MW
WHERE T_MW.CompanyID = 2
AND 
(
    (
       @Currency IS NOT NULL
       AND 
       T_MW.Currency IN 
       (
          SELECT * FROM #Currency
       )
    )
    OR
    @Currency IS NULL
)
AND 
(
    (
       @Asset IS NOT NULL
       AND
       T_MW.Asset IN 
       (
            SELECT * FROM #Asset
        )
    )
    OR
    @Asset IS NULL
)

答案 1 :(得分:0)

SELECT 
T_MW.*
INTO #temp
FROM T_MWP T_MW
WHERE T_MW.CompanyID = 2
AND 
(
(
   @Currency IS NOT NULL
   OR 
   T_MW.Currency IN 
   (
      SELECT * FROM #Currency
   )
)
)
AND 
(
(
   @Asset IS NOT NULL
   OR
   T_MW.Asset IN 
   (
        SELECT * FROM #Asset
    )
)
)