0

我有两张桌子。user并且user_new 包含user旧数据。包含user_new新数据。我想同步user_newuser.

  1. 如果数据存在于user_new,不存在于user,则插入到user
  2. 如果数据存在于userand中user_new,则更新。(与列比较id

什么是快速的 sql 来做到这一点?

4

4 回答 4

2

这适用于任何服务器版本 -

   -- 1) Insert new record

        INSERT INTO old_table(id, column)
        SELECT n.id, n.column
        FROM new_table n
        LEFT JOIN old_table o ON n.id = o.id
        WHERE o.id IS NULL

   -- 2) Update existed record

        UPDATE o
        SET column = n.column
        FROM old_table o
        JOIN new_table n ON n.id = o.id
于 2013-04-17T09:09:33.137 回答
1

从 Sql Server 2008 起,您可以使用Merge语法

MERGE user target
USING user_new source
ON taget.ID = source.ID
WHEN MATCHED THEN
UPDATE
SET target.Column= source.Column1,target.column2=source.column2
WHEN NOT MATCHED BY TARGET THEN
INSERT (ID,Column1,Column2)
VALUES (source.ID,source.column1,source.column2);

或者您可以使用以下查询

INSERT INTO user(ID,column1,column2) 
SELECT ID,column1,column2 FROM user_new  AS source
WHERE NOT EXISTS (SELECT * FROM user WHERE ID = source.ID);

UPDATE target SET ...
FROM user AS target
INNER JOIN user_new AS source
ON target.ID = source.ID;
于 2013-04-17T09:14:19.480 回答
0

如果您有 sql server 2008+,听起来您可能需要合并。

于 2013-04-17T09:12:56.303 回答
0

你不能这样做insert,并且update在一个查询中你必须单独做

select * from user where user_id not in (select user_new.user_id from user_new )

此查询会导致插入查询的数据类似地您必须通过替换not in来更新in

于 2013-04-17T09:10:26.467 回答