Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Two tables merge

Author  Topic 

alhakimi
Starting Member

23 Posts

Posted - 2013-05-21 : 06:54:34
Dear friends

I have two tables 90% similar to each other for example :

table 1
column1 column2 column3 column4

table 2

column1 column2 column3 column4 column5

i want to put both data in one table how can i do that ?

thank you and B. Regards

Hakimi

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-05-21 : 07:15:37
so which table would have final result? what will happen to data in column5?

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page

alhakimi
Starting Member

23 Posts

Posted - 2013-05-21 : 13:40:55
Hi ,

I don't have any problem in having the data in any of those tables also i can have third table if needed.
in regards to the column4 i don't need it.

Go to Top of Page

James K
Master Smack Fu Yak Hacker

3873 Posts

Posted - 2013-05-21 : 14:51:38
IF there is a primary key on the tables, join them on the primary key and insert into the third table. For the example you have shown below, assuming col1 is the primary key and assuming if there are conflicts you want to give preference to values in Table 1:
INSERT INTO YourThirdTable
(col1, col2, col3, col4, col5)
SELECT
COALESCE(a.col1,b.col1),
COALESCE(a.col2,b.col2),
COALESCE(a.col3,b.col3),
COALESCE(a.col4,b.col4),
b.col5
FROM
Table1 a
FULL JOIN Table2 b ON a.col1 = b.col1;
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-05-22 : 00:36:51
Hmm...my understanding on requirements was to merge both the resultsets onto same table. That being the case, I would have done it like below


INSERT YourThirdTable
SELECT col1, col2, col3, col4
FROM Table1
UNION
SELECT col1, col2, col3, col4
FROM Table2


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page
   

- Advertisement -