Quantcast
Channel: SQLServerCentral » SQL Server 2014 » Development - SQL Server 2014 » Latest topics
Viewing all articles
Browse latest Browse all 3145

Merge two tables and insert/update respectively

$
0
0
I have two tables and I have to merge the records.source:ID seq name designation company001 1 aaa Developer YYY001 2 aaa lead yyy002 1 mmm consultant bbb003 1 ppp developer yyy003 2 ppp lead yyy003 3 ppp manager yyytarget:ID seq name designation company001 1 aaa Developer YYY001 2 aaa lead yyy002 1 mmm consultant bbb003 1 ppp developer yyy003 2 ppp lead yyy003 3 ppp manager yyyI want to write merge to insert/update records. My key columns are ID and seq both.they are composite primary keys. generally it is an update record we get. For example, ID 001 has two records in source . if ID 001 gets another record with sequence 3 , then this record should go as an insert in target.if my source now has source:ID seq name designation company001 1 aaa Developer YYY001 2 aaa lead yyy001 3 aaa manager yyy002 1 mmm consultant bbb003 1 ppp developer yyy003 2 ppp lead yyy003 3 ppp manager yyythen target should be: target:ID seq name designation company001 1 aaa Developer YYY001 2 aaa manager yyy001 3 aaa manager yyy002 1 mmm consultant bbb003 1 ppp developer yyy003 2 ppp lead yyy003 3 ppp manager yyyI am trying with below merge and it is not working for me.MERGE target t using source s on s.ID=t.ID and s.seq=t.seqwhen not matchedthen Insert(ID,seq,name,designation,company)Values(s.ID,s.seq,s.name,s.designation,s.company)when matchedthen updatesetname=s.name,designation=s.designation,company=s.company;Can you please let me know where am I going wrong? any help is appreciated

Viewing all articles
Browse latest Browse all 3145

Trending Articles