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
 Union Multiple Tables With Different Columns

Author  Topic 

haler
Starting Member

13 Posts

Posted - 2011-12-19 : 19:04:45
Hi,

What i am trying to do is merge multiple tables together into one table. All tables follow the same column name template but some tables do not have that column. I have tried using union but it requires the table to have the same columns exactly.

for example

table 1
site, name, rawAddress, streetAddress, phone, facebook

table 2
site, name, rawAddress, streetAddress, phone, facebook

table 3
site, name, rawAddress, streetAddress, phone, fax, facebook

table 4
site, name, rawAddress, streetAddress, phone, fax

How would i go about merging all the tables into one table based on their column name.

Thanks

singularity
Posting Yak Master

153 Posts

Posted - 2011-12-19 : 19:08:34
[code]
select site, name, rawAddress, streetAddress, phone, null as fax, facebook
from table1
union all
select site, name, rawAddress, streetAddress, phone, null as fax, facebook
from table2
union all
select site, name, rawAddress, streetAddress, phone, fax, facebook
from table3
union all
select site, name, rawAddress, streetAddress, phone, fax, null as facebook
from table4
[/code]
Go to Top of Page

haler
Starting Member

13 Posts

Posted - 2011-12-19 : 19:16:58
Is there a way to do this without having to check each table to see whether the column is there or not?
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-12-19 : 22:27:55
what does that mean? does that mean field doesnt even exist in table or is it like its existing with empty/null values?

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

haler
Starting Member

13 Posts

Posted - 2011-12-19 : 22:52:08
it means the field doesnt exist in some tables
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-12-20 : 00:09:42
then as shown above you need to put a place holder for that as union/union all requires all seperated queries to have same number of columns and corresponding field datatypes should be compatible with each other

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -