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
 SQL Server 2008 Forums
 Transact-SQL (2008)
 replace rows with a table

Author  Topic 

zhshqzyc
Posting Yak Master

240 Posts

Posted - 2012-06-21 : 08:27:30
Hello,
I have a datatable generate from an application. All rows in the table have the same vlaues in the second column.(Not Primary Key). I want to replace the rows in a database table in SQL server 2008 R2 which have the same column values.

That means:
1. If rows are not in the database table, insertion.
2. If rows are in the database table, updatation.
3. If rows are not in the new table but in Sql Server, deletion.

Thanks for help.

nigelrivett
Master Smack Fu Yak Hacker

3385 Posts

Posted - 2012-06-21 : 08:30:52
not really sure what yoou want but maybe

merge table1 t1
using table2 t2
on t1.id = t2.id
when matched then update set colb = t2.colb
when not matched by target then insert
(id, colb)
values (t2.id,t2.colb)
when not matched by source then delete;


==========================================
Cursors are useful if you don't know sql.
SSIS can be used in a similar way.
Beer is not cold and it isn't fizzy.
Go to Top of Page

zhshqzyc
Posting Yak Master

240 Posts

Posted - 2012-06-21 : 08:43:14
Yes. That is what I want.
For the delete part, do I need where clause?
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-06-21 : 18:19:01
nope..thats what when not matched by source means

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -