将IF转换为WHERE子句

时间:2013-04-11 18:34:38

标签: sql sql-server

以下作品

IF OBJECT_ID('TEMPDB..#Users') IS NOT NULL 
BEGIN 
    DROP TABLE #Users 
END;

CREATE TABLE #Users(UserAccountKey INT);

IF @Period IN ('Overall', 'Week1', 'Week2', 'Week3', 'Week4') 
BEGIN
   INSERT INTO #Users
      SELECT UserAccountKey
      FROM XXX c
      WHERE c.Name NOT IN ('X', 'Y', 'Z', 'J', 'Q')
      GROUP BY UserAccountKey
END
ELSE
BEGIN
   INSERT INTO #Users
      SELECT UserAccountKey
      FROM XXX c
      WHERE c.Name NOT IN ('X', 'Y')
      GROUP BY UserAccountKey;
END;

是否可以将其缩短为单个sql语句?可以将IF条件转移到WHERE子句吗?

4 个答案:

答案 0 :(得分:3)

可以简化一点:

  INSERT INTO #Users
  SELECT UserAccountKey
  FROM XXX c
  WHERE c.Name NOT IN ('X', 'Y')
        OR (@Period IN ('Overall', 'Week1', 'Week2', 'Week3', 'Week4')
             AND c.Name NOT IN ('Z', 'J', 'Q'))
  GROUP BY UserAccountKey

答案 1 :(得分:2)

处理此问题的最佳方法是将if转换为单一条件。我相信这会产生同样的结果:

   INSERT INTO #Users
      SELECT UserAccountKey
      FROM XXX c
      WHERE (@Period NOT IN ('Overall', 'Week1', 'Week2', 'Week3', 'Week4')
             and c.Name NOT IN ('X', 'Y'))
         or (@Period IN ('Overall', 'Week1', 'Week2', 'Week3', 'Week4')
            and c.Name NOT IN ('X', 'Y', 'Z', 'J', 'Q'))
      GROUP BY UserAccountKey

这一直困扰着我,因为我认为它应该能够简化,但我无法弄清楚如何。我的原始答案与@ Pirion相同,但我改变了它,因为我意识到它不会等同于原始脚本。下面是一个简化的脚本,我认为它提供了与我之前的答案相同的功能:

   INSERT INTO #Users
      SELECT UserAccountKey
      FROM XXX c
      WHERE not (c.Name IN ('X', 'Y')
                 or (@Period IN ('Overall', 'Week1', 'Week2', 'Week3', 'Week4')
                     and c.Name IN ('Z', 'J', 'Q'))
      GROUP BY UserAccountKey

答案 2 :(得分:1)

INSERT INTO #Users
SELECT userAccountKey
FROM XXX c
WHERE ( c.Name NOT IN ('X','Y','Z','J','Q')
AND @Period IN ('Overall','Week1','Week2','Week3','Week4'))

OR
(
c.Name NOT IN ('X','Y')
AND @Period NOT IN ('Overall','Week1','Week2','Week3','Week4')
)
GROUP BY UserAccountKey

答案 3 :(得分:0)

INSERT INTO #Users
SELECT userAccountKey
FROM XXX c
WHERE c.Name NOT IN ('X','Y','Z','J','Q')
AND @Period IN ('Overall','Week1','Week2','Week3','Week4')
GROUP BY UserAccountKey

INSERT INTO #Users
SELECT UserAccountKey
FROM xxx C
WHERE c.Name NOT IN ('X','Y')
AND @Period NOT IN ('Overall','Week1','Week2','Week3','Week4')
GROUP BY UserAccountKey