MSSQL Query用于比较和复制(同步)一个列/表到另一个列/表的值

时间:2017-10-18 07:21:18

标签: sql-server

有人可以帮助我吗?我不是MSSQL专家,需要构建这种一次性查询来进行某种表同步

我正在寻找一种方法,将表A中一列的值复制到表B中的另一列,这是基于B列中不存在该值的条件。还要从表B中删除值如果表A中不存在(同样这是同一列)。

我有两个看起来像这样的表(还没有内嵌的图像发布):

dbo.EM_T_USERS

enter image description here

dbo.em_T_PRESENCE_USER_CONFIG

enter image description here

如果您需要更多信息,请告诉我......

RGDS,

大卫

  • 编辑 - 添加图像以说明表格

2 个答案:

答案 0 :(得分:0)

以下是您正在寻找的解决方案:

DECLARE @Target TABLE (EmployeeID INT PRIMARY KEY, EmployeeName VARCHAR(10))

DECLARE @Source TABLE(EmployeeID INT PRIMARY KEY, EmployeeName VARCHAR(10));


INSERT @Target(EmployeeID, EmployeeName) VALUES(100, 'Mary');
INSERT @Target(EmployeeID, EmployeeName) VALUES(101, 'Sara');
INSERT @Target(EmployeeID, EmployeeName) VALUES(102, 'Stefano');


INSERT @Source(EmployeeID, EmployeeName) Values(103, 'Bob');
INSERT @Source(EmployeeID, EmployeeName) Values(104, 'Steve');
INSERT @Source(EmployeeID, EmployeeName) Values(105, 'Sara');



MERGE @Target AS T
USING @Source AS S
ON (T.EmployeeID = S.EmployeeID) 
WHEN NOT MATCHED BY TARGET AND S.EmployeeName LIKE 'S%' 
    THEN INSERT(EmployeeID, EmployeeName) VALUES(S.EmployeeID, S.EmployeeName)
WHEN MATCHED 
    THEN UPDATE SET T.EmployeeName = S.EmployeeName
WHEN NOT MATCHED BY SOURCE AND T.EmployeeName LIKE 'S%'
    THEN DELETE 
OUTPUT $action, inserted.*, deleted.*;

SELECT * FROM @Target

答案 1 :(得分:0)

感谢您提供的所有提示和见解,但我找到了一个设置tiggers的解决方案,当表A更改时,它将反映表B中的更改。 很遗憾,我自己没有建立这些触发器,我得到了一位同事的帮助..

Rgds,大卫