question

ravi_vaishya avatar image
ravi_vaishya asked

regarding inserting data from three tables having same fields

i am trying to insert the data into a single table by selecting the data from three tables having the same columns in all the tables....

please help me out

thanks in advance

sql server 2014
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

1 Answer

·
Jon Crawford avatar image
Jon Crawford answered

Assuming that you want to append the data from each table into the existing columns:

INSERT INTO targetTable (column1, column2, ... columnN)
SELECT column1, column2 ... columnN FROM table1
UNION ALL
SELECT column1, column2 ... columnN FROM table2
UNION ALL
SELECT column1, column2 ... columnN FROM table3

If, however, you want to show all the columns grouped into one table (and if this is the case, why? Now you have a copy of the data from those tables that has to stay in sync?) then you need to join the tables and give the columns in the resulting table aliases that make sense to you:

INSERT INTO targetTable (column1, column2, tbl2col1, tbl2col2, tbl3col1, tbl3col2)
SELECT table1.column1, table1.column2, 
table2.column1 AS tbl2col1, table2.column2 AS tbl2col2,
table3.column1 AS tbl3col1, table3.column2 AS tbl3col2
FROM table1
JOIN table2 ON table1.key = table2.key
JOIN table3 ON table3.key = table1.key
WHERE someCondition = 'true';
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.