insert data to table from another table

hello,
how can i insert data to table1 from table2?
table1 have relation with another tables and have primmary and foreign key ,so i have problem,
please help me.
z1357_khAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

SimonLarsenCommented:
For each of your foreign keys you'll need to do:

insert into LookupTable
Select distinct (ForignKey) from Table2

then do your insert from table2.
0
LowfatspreadCommented:
as simon has indicated
you first need to insert the parent rows to the related tables...

and then you can do the insert into Table1 from table2


is this a one-off or a normal requirement ?

if its going to be part of your standard requirements and all the data is present
you may like to investigate BEFORE or INSTEAD OF TRIGGERS  
on the tables or a new view


hth
0
z1357_khAuthor Commented:
please describe more,
table1 has relation with table3 and no relation with table2
fields in table1 and table2 is equal.
please indicate all commands
thanks
0
SimonLarsenCommented:
yah so you need in table3, say, the value Elephant before you can put it into table1 from table2.

So:

Insert into table3 (ColumnName)
select distinct (t2.foreignKeyColumn)
from table2 t2 left join
      table3 t3
on t2.ForignKeyColumn = t3.ColumnName
where t3.ColumnName is null

do this for each relationship.

Then:

Insert into table1 (Col1, Col2, Col3)
select Col1, Col2, Col3 from table2
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.