简体   繁体   English

从源到目标评估每个字段并进行更新

[英]Evaluate each field from source to target and update

I am using Microsoft Sql server 2014 我正在使用Microsoft SQL Server 2014

I have a request where i have to check if ID exists ,If ID exists then update. 我有一个要求,我必须检查ID是否存在,如果ID存在,则进行更新。 However client wants to evaluate each field from source and check if there are any changes in target, if there are any changes update only that field and rest of the fields should be original. 但是,客户希望评估源中的每个字段,并检查目标中是否有任何更改,如果有任何更改,则仅更新该字段,其余字段应为原始字段。

So if my original request is, Source : 因此,如果我最初的要求是Source:

ID name company salary
1 dave ABC 50000$
2 ashley XXX 50000$

Target: 目标:

ID name company salary
1 dave ABC 50000$
2 ashley XXX 50000$

Updated request: Source : 更新的请求:来源:

ID name company salary
1 dave ABC 80000$
2 ashley XXX 80000$

Now I have to check each column to see if there are any changes , only if any column has any change then update only that field. 现在,我必须检查每列以查看是否有任何更改,只有任何列有任何更改,然后才更新该字段。

target: 目标:

ID name company salary
1 dave ABC 80000$
2 ashley XXX 80000$

I cannot use hashkey/flag field as my target table does not have these fields and I cannot alter them. 我无法使用hashkey / flag字段,因为我的目标表没有这些字段,因此无法更改它们。 What is the best way to do this? 做这个的最好方式是什么? Any help is appreciated 任何帮助表示赞赏

You can build a dinamic update query server side testing the value or you can use an update with inner join and case statement If you use mysql you can try this way 您可以构建一个动态更新查询服务器端来测试该值,也可以使用带有内部联接和case语句的更新如果使用mysql,则可以尝试这种方式

update target t
inner join source s on t.id = s.id
set case when t.name <> s.name then s.name else t.name end,
    case when t.company <> s.company then s.company else t.company end,
    case when t.salary <> s.salary then s.salary else t.salary end     

Thank you guys! 感谢大伙们! this solution works 此解决方案有效

 MERGE testdb.dbo.targettable r
using dbo.sourcetable s
on s.id=r.id
WHEN MATCHED THEN
UPDATE 
SET column1 = CASE WHEN r.column1 <> s.column1 THEN s.column1 ELSE r.column1 END,
column2 = CASE WHEN r.column2 <> s.column2 THEN s.column2 ELSE r.column2 END,
column3 = CASE WHEN r.column3 <> s.column3 THEN s.column3 ELSE r.column3 END,
column4 = CASE WHEN r.column4 <> s.column4 THEN s.column4 ELSE r.column4 END,
column5 = CASE WHEN r.column5 <> s.column5 THEN s.column5 ELSE r.column5 END,
column6 = CASE WHEN r.column6 <> s.column6 THEN s.column6 ELSE r.column6 END

....... ; .......;

I was looking if there is any query that can be written dynamically ie dynamically checking if any column needs update from source to target and update the target tables rather than checking each column. 我一直在寻找是否有可以动态编写的查询,即动态检查是否有任何列需要从源更新到目标并更新目标表,而不是检查每个列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM