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
 copying of a row to anothe table

Author  Topic 

Leo_Don
Starting Member

42 Posts

Posted - 2008-10-30 : 05:23:01
Hello friends,

I want to copy a row from one tabel to the other...

for eg i have two tabel t1 and t2

table t1

name id address
---------------------
xyz 1 xysdsa
asd 2 dewsd
qwe 3 asajasd




tabel t2

name id address
---------------------
asd 2 dewsd
qwe 3 asdjasd


I want to copy the whole 1st row with id 1 of table t1 to t2


thanx in advance

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-10-30 : 05:29:58
[code]insert into table2
select name,id,address
from table1 t1
left join table2 t2
on t2.id=t1.id
and t2.name=t1.name
where t2.id is null[/code]
Go to Top of Page

Leo_Don
Starting Member

42 Posts

Posted - 2008-10-30 : 05:41:00
quote:
Originally posted by visakh16

insert into table2
select name,id,address
from table1 t1
left join table2 t2
on t2.id=t1.id
and t2.name=t1.name
where t2.id is null




Thanx for the Reply...
can we se the below query as well

insert into table2
select *
from table1 t1
left join table2 t2
on t2.id=t1.id
and t2.name=t1.name /* and can this alos be ignored*/
where t2.id is null and t2.name is null /* are we using this coz we insert into a null row*/
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-10-30 : 05:44:18
nope. the last condition is to ensure we insert only those records which are not already in table2. the join should involve all columns which forms part of your primary key. (i gave id & name as i thought they make up the primary key)
Go to Top of Page

Leo_Don
Starting Member

42 Posts

Posted - 2008-10-30 : 05:49:55
And i think we are not checking the condition where the row should have the id = 1.

i.e i want to copy only the row with id = 1 and name = xyz
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-10-30 : 06:06:53
oh...so just single row. then only this is reqd.

insert into table2
select *
from table1 t1
where id = 1 and name = 'xyz'


i thought your attempt was to enter all records to table2 which are in table1 and does not exist already in table2
Go to Top of Page

Leo_Don
Starting Member

42 Posts

Posted - 2008-10-30 : 06:19:06
thank yo
Go to Top of Page
   

- Advertisement -