Click here to Skip to main content
15,896,549 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi, Friends I have Three Tables in my database, Table1 has 10 columns, Table2 Has 1 column, I Create the Table3 that contains 11 columns, How to insert Table1 values in Table3 first 10 columns and table 2 value in table3 last column.


SQL
insert into Table3(col1,col2,....,col11) VALUES SELECT * FROM TABLE1 UNION SELECT * FROM TABLE2


I know this code is not correct, help me to correct it
Posted
Comments
RossMW 19-Jun-15 2:46am    
Unless you have a link (or common reference field) between table2 and table1 then you can't align the data to the correct row. Or are you just trying to append the data one table after the other?
Member 11724596 19-Jun-15 2:55am    
I want merge the two table datas in single table
RossMW 19-Jun-15 3:02am    
Yes but are you expecting table3 to have table1 data followed by table2 data in completely seperate rows. i.e. If you just run two seperate insert statements

1 solution

A table with one column can't be associated with data in a different table - unless it's a foreign key column, but then the foreign key data is already in the other table already! :laugh:

SQL rows aren't ordinal: SQL is at liberty to return rows in any order it finds convenient unless a specific ORDER BY clause is present in the query - so having two tables where the data has been entered in a specific order does not guarantee any ordering to the data when it is selected from the two tables - and the order you get with the same query is not necessarily going to be the same as the same query run a second later, if SQL has reorganised the data for any reason it feels it should.

So in practice, you can't do it - at least not in SQL - as you need a JOIN to "combine" the tables and you have no linking field.

As a one off, you could use C# or VB (for example) to SELECT all of the rows from each table in separate queries and then write a third query to combine them - or you could SELECT then into two temporary tables with a ROWCOUNT on each and use that at the linking field for the JOIN.

But either way, you are going to have to be very, very careful of exactly what data you end up with and check it very carefully to ensure your data integrity.

Me? I'd add a new row to the original table in the designer, and enter the "new data" from the second table again to make sure it goes to the right row each time.
 
Share this answer
 
Comments
RossMW 19-Jun-15 4:04am    
I wasn't sure if it was a join requirement or a union all as per the sample. But a good complete answer for a join requirement

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900