Sql-Server

返回條件 where 子句中的值列表

  • September 12, 2017

我正在嘗試根據一個參數過濾一個表,該參數確定某個列允許哪些值列表。因為@Parameter = 1我們想MyColumn成為FirstValueSecondValue;因為@Parameter = 2我們想MyColumn成為ThirdValueFourthValue;否則我們想要 的所有值MyColumn

這種語法顯然不起作用:

declare @Parameter int = 1; -- can also be 2 or 3

select * 
from dbo.MyTable 
where MyColumn in 
(
   case @Parameter
       when 1 then (N'FirstValue', N'SecondValue') 
       when 2 then (N'ThirdValue', N'FourthValue') 
       else (N'FirstValue', N'SecondValue', N'ThirdValue', N'FourthValue') 
   end
);

實現這一目標的最佳方法是什麼?

**編輯:**這可行,但確實很笨重,所以我想找到一個更優雅的解決方案:

select * 
from dbo.MyTable 
   join 
   (
       values 
       (1, N'FirstValue'),
       (1, N'SecondValue'),
       (2, N'ThirdValue'),
       (2, N'FourthValue'),
       (3, N'FirstValue'),
       (3, N'SecondValue'),
       (3, N'ThirdValue'),
       (3, N'FourthValue')
   ) as temp(Option, Value)
   on MyTable.MyColumn = temp.Value
where temp.Option = @Parameter;

除非我遺漏了什麼,否則這個“看起來”就像是一個簡單的組合 AND 和 OR 條件的案例

Declare @Parameter int = 1
declare @MyTable table(id int, MyColumn nvarchar(100))
insert into @MyTable
values(1, N'FirstValue'), (1, N'SecondValue'), (2, N'ThirdValue'), (2, N'FourthValue'), (5, N'FifthValue')

SELECT *
FROM @MyTable
WHERE (
       @Parameter = 1
       AND (
           MyColumn = 'FirstValue'
           OR MyColumn = 'SecondValue'
           )
       )
   OR (
       @Parameter = 2
       AND (
           MyColumn = 'ThirdValue'
           OR MyColumn = 'FourthValue'
           )
       )
   OR (
       @Parameter <> 1
       AND @Parameter <> 2
       )

使用CASE表達式的等價物是

Declare @Parameter int = 3
declare @MyTable table(id int, MyColumn nvarchar(100))
insert into @MyTable
values(1, N'FirstValue'), (1, N'SecondValue'), (2, N'ThirdValue'), (2, N'FourthValue'), (5, N'FifthValue')

SELECT *
FROM @MyTable
WHERE 'Y' = CASE 
       WHEN @Parameter = 1
           AND MyColumn IN (
               N'FirstValue'
               ,N'SecondValue'
               )
           THEN 'Y'
       WHEN @Parameter = 2
           AND MyColumn IN (
               N'ThirdValue'
               ,N'FourthValue'
               )
           THEN 'Y'
       WHEN @Parameter NOT IN (
               1
               ,2
               )
           THEN 'Y'
       ELSE 'N'
       END

引用自:https://dba.stackexchange.com/questions/185680