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)
 Insert or update a table

Author  Topic 

zhshqzyc
Posting Yak Master

240 Posts

Posted - 2012-06-05 : 10:43:33
I have a table that has four columns. The first column sKey is the promary key.
I have an C# application in which generate DataRows. I want to insert rows to the table. The question is that the rows may be existing. In this case, just update the records. If not insert rows then.

Here is the unfinished code and also there is error.
Thanks.
Insert into MetTable(skey,col1,col2,col3) Values(@skey,@col1,@col2,@col3)
WHERE NOT EXISTS
(Select * from MetTable)

nigelrivett
Master Smack Fu Yak Hacker

3385 Posts

Posted - 2012-06-05 : 10:51:15
Have a look at the merge statement

http://www.nigelrivett.net/Products/DWBuilder/MergeForAuditTrail.html

;with cte as (select skey=@skey,col1=@col1,col2=@col2,col3=@col3)
merge MetTable d
using cte s
on s.skey = d.skey
when matched then update
set col1=s.col1 ,
...
when not matched by target then inserrt
(skey, col1, ...)
values (s.skey, s.col1,...);

==========================================
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
   

- Advertisement -