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
 Insert From Multiple Tables into One Table

Author  Topic 

haler
Starting Member

13 Posts

Posted - 2011-12-20 : 23:48:11
Hi what i am trying to do is insert all my data from multiple tables into the one table. The fields have the same naming convention but for some tables the field might not exist. I have a table with a list of all the table names i want to insert into the master table.

so for example my master table would look like this

company | name | address | phone | fax | email | facebook

and then i have multiple tables with the same field names but some fields might not exist so it would be like so

table 1
company | name| phone | fax

table 2
company | name | addresss | phone | email

table 3
company | name | address | facebook | phone

Am i able to loop through my list of tables and insert the contents into the appropriate fields and how would i go about doing so?

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2011-12-21 : 00:33:05
You would join them together to produce the layout that you want.

insert into masterTable (...)
select t1.c1, t1.c2, t2.c9, t2.c10, t3.c4
from t1
join t2 on t1.c1 = t2.c1
join t3 on t2.c1 = t3.c1

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page

haler
Starting Member

13 Posts

Posted - 2011-12-21 : 00:45:46
Is there a more streamlined way of doing this, maybe looping through my list of table names? because I may have hundreds of tables that need to be inserted.

Also i dont think a join is what i am looking for, It is more like a union but union wont do what i want to do.
Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2011-12-21 : 00:48:16
You could certainly write code to do it, but that'll take a lot of work. You'll need to use dynamic SQL for this. Not knowing what columns are in what tables will make the dynamic SQL code challenging. It's certainly doable though, just will take a lot of time to write. There's nothing built-in to help you with this.

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page
   

- Advertisement -