合并相同的目标和源表

时间:2012-02-07 15:07:01

标签: sql sql-server-2008

我有一个表,我想检查记录是否存在,如果不插入新行并更新上一行,请单独留下。我想知道我是否可以像下面这样使用合并?

  CREATE TABLE a
  (keycol INT PRIMARY KEY,
  col1 INT NOT NULL,
  col2 INT NOT NULL,
  col3 INT NOT NULL);

INSERT INTO a VALUES (1,0,0,0),(2,0,0,0);

MERGE INTO a
USING select 1 from a where col1 = 3
WHEN NOT MATCHED THEN
UPDATE SET
col2 = 2,
col2 = 2,
col3 = 2
where col1 = 3
WHEN NOT MATCHED THEN   
INSERT (keycol, col1, col2, col3)
VALUES (4, 0, 0, 0)

谢谢,

1 个答案:

答案 0 :(得分:3)

MERGE INTO a
   USING (
          VALUES (3,3,2,2),
                 (4,0,0,0)
         ) AS source (keycol, col1, col2, col3)
   ON a.keycol = source.keycol
      AND a.col1 = source.col1
WHEN MATCHED THEN
   UPDATE 
      SET col2 = source.col2,
          col3 = source.col3
WHEN NOT MATCHED THEN   
   INSERT (keycol, col1, col2, col3)
      VALUES (keycol, col1, col2, col3);