拿走EXISTS但留在开关中

时间:2013-03-12 19:52:17

标签: sql sql-server-2012

如何修改最终脚本还有一个排除开关?我不想在最终脚本中使用EXISTS

SELECT MyField = 'x' INTO #Data
UNION SELECT MyField = 'y'
UNION SELECT MyField = 'z'
UNION SELECT MyField = 'j'
UNION SELECT MyField = 'q'
UNION SELECT MyField = NULL;

SELECT MyField = 'j' INTO #Exclusions
UNION  SELECT MyField = 'q'
UNION SELECT MyField = NULL;


DECLARE @ShowAll TINYINT = 1; -->>exceptions "switch" is turned ON so all data returned
SELECT *
FROM   #Data d
WHERE  @ShowAll = 1 OR 
       (
       EXISTS
         (
         SELECT d.MyField 
         EXCEPT
         SELECT MyField FROM #Exclusions
         )
       );

--can I simplify and get rid of the EXISTS but still include a switch based on @ShowAll ? 
SELECT *
FROM   #Data d
       EXCEPT
       SELECT MyField FROM #Exclusions;

2 个答案:

答案 0 :(得分:3)

SELECT *
FROM   #Data d
       EXCEPT
       SELECT MyField FROM #Exclusions WHERE @ShowAll <> 1;

http://sqlfiddle.com/#!6/d41d8/3125

答案 1 :(得分:0)

将其包装在存储过程中并将开关作为选项传递。