SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Two tables merge
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

alhakimi
Starting Member

Yemen
23 Posts

Posted - 05/21/2013 :  06:54:34  Show Profile  Reply with Quote
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

India
52317 Posts

Posted - 05/21/2013 :  07:15:37  Show Profile  Reply with Quote
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

Yemen
23 Posts

Posted - 05/21/2013 :  13:40:55  Show Profile  Reply with Quote
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
Flowing Fount of Yak Knowledge

3704 Posts

Posted - 05/21/2013 :  14:51:38  Show Profile  Reply with Quote
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

India
52317 Posts

Posted - 05/22/2013 :  00:36:51  Show Profile  Reply with Quote
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
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.14 seconds. Powered By: Snitz Forums 2000