Merging two SQL Server tables conditionally into a third table -


Obviously, I'm not a SQL person, so I have to ask for help on simple tasks from the following.

I have two SQL Server 2008 tables: t1 and t2 several identical columns and one key column ( entry_ID ) with. T2 rows that are not present in t1 , but should.

I want to merge those rows with t2 which is not present in t1 , but from me t2 No line that is already present in t1 I want to set the result to fill the new t3

I have seen many solutions online, but the above scenario can not be resolved.

Thank you.

There are several ways to do this UNION ALL or OUTER JOIN .

Assuming that you are using Entry_ID to find similar records, and Entry_ID is unique within each table, here is a OUTER JOIN method:

This receives your record set: T1 and T2 are merged:

  Select when T1.Entry_ID then 'T2' when T is 2.Entry_ID then ' T1 'All other' both 'end SourceTable, COALESCE (T1.Entry_ID, T2.Entry_ID) Entry_ID, COALESCE (T1.Col1, T2.Col1) Col1, COALESCE (T1.Col2, T2.Col2) Col2, COALESCE As (T1 Col3, T2.Col3) Col3, COALESCE (T1.Col4, T2.Col4) Col4 As T1 in complete form T1.Entry_DI = T2.Entry_ID join the order T2 COALESCE (T1.Entry_DI, T2.Entry_ID)  

This is included in T3 Does:

  Select T3 (Entry_ID, Col1, col2, Col3, Col4) as entry into COALESCE (T1.Entry_DI, T2.Entry_ID). Entry_ID, Collages (T1. Call 1, T2. Cole 1) Coal 1, Coalus (T1 Col2, T2.Col2) Col2, COALESCE (T1.Col3, T2.Col3) Col3, COALESCE (T1.Col4, T2.Col4) T1 Full Exterior Join as T1.Entry_DI = T2.Entry_ID  

Then you can T must Entry_ID that must be unique within their tables, and it is used to match between the tables.

Also note the column from the selection row column list in the included statement - the order of the columns in the physical table does not make any difference, INSERT and SELECT will simply line up.


Comments

Popular posts from this blog

ios - How do I use CFArrayRef in Swift? -

eclipse plugin - Run java code error: Workspace is closed -

c - Error on building source code in VC 6 -