2

以下の作品

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

4 に答える 4

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
于 2013-04-11T21:01:25.437 に答える
2

ifこれを処理する最善の方法は、を 1 つの条件に変換することです。これで同じ結果が得られると思います:

   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
于 2013-04-11T18:42:13.453 に答える
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
于 2013-04-11T18:43:19.557 に答える
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
于 2013-04-11T18:41:06.973 に答える