如何选择INTO并在插入前检查每一行

时间:2014-01-16 23:09:54

标签: sql sql-server-2008

我想使用SELECT INTO创建一个表,但希望避免创建两个列相等但与另外两列不同的行。例如,假设我有一个生成以下数据的查询

+----+----+
|col1|col2|
+----+----+
|A   |XYZ |
+----+----+
|2   |4   |
+----+----+
|WA  |AB  |
+----+----+
|W   |B   |
+----+----+
|XYZ |A   |
+----+----+

在这种情况下,我想添加除最后一行之外的所有行,因为它是第一行的翻转副本。这是我目前所获得的概念版本:

SELECT
    a.col1 AS col1,
    b.col1 AS col2,
INTO newTable
FROM a
INNER JOIN b
    ON -- some match criteria
-- If I were to end the query here, it would generate the table shown above

-- my attempt at avoiding cross duplicates:
WHERE NOT EXISTS ( 
    SELECT x.col1,x.col2
    FROM -- what name do I use here? AS x
    WHERE (x.col1 = col2 AND x.col2 = col1)
)

请注意,之前生成代码的条件外WHERE块非常大,我宁愿不必在NOT EXISTS块中重复它。我该如何处理这个问题?

1 个答案:

答案 0 :(得分:2)

SELECT DISTINCT
  CASE WHEN col2 > col1 THEN col1 ELSE col2 END,
  CASE WHEN col2 > col1 THEN col2 ELSE col1 END
FROM newTable