tags:

views:

112

answers:

3

I'm hoping to use the following update\insert method to speed up my application insert\updates:

UPDATE [Application_Type_Table] 
SET ApplicationType='Test Value'
WHERE ID='1'
IF @@ROWCOUNT=0
INSERT INTO [Application_Type_Table] VALUES ('Test Value')

How would I do this with sql parameters? the rowcount function will be picked up as a parameter due to the @@.

sqlCommand.CommandText = _
"UPDATE [Application_Type_Table]" _ 
SET (SET ApplicationType=@TestValue" _ 
"WHERE ID=@RecordID IF @@ROWCOUNT=0 INSERT INTO [Application_Type_Table] VALUES (@TestValue)"

http://blogs.msdn.com/b/miah/archive/2008/02/17/sql-if-exists-update-else-insert.aspx

A: 

I would suggest moving the query to a stored procedure. Queries (especially multi-statement ones) don't really belong hard-coded into one's application IMO. Doing so would also have the bonus of alleviating your problem ;)

Ken
A: 
sqlCommand.CommandText = "IF NOT EXISTS (SELECT 1 FROM  [Application_Type_Table] WHERE "_
"ID='1') BEGIN INSERT INTO " _
"[Application_Type_Table] VALUES ('Test Value') END ELSE BEGIN UPDATE [Application_Type_Table]"_
"SET ApplicationType='Test Value'"_
"WHERE ID='1' END"
Anil
+2  A: 

This pattern is known as an UPSERT. The modern way of doing this is to use MERGE in SQL Server 2008 e.g.

MERGE INTO Application_Type_Table AS target 
USING (
       VALUES (@RecordID, @TestValue)
      )  AS source (ID, ApplicationType)
   ON target.ID = source.ID
WHEN MATCHED 
   THEN UPDATE 
           SET ApplicationType = source.ApplicationType
WHEN NOT MATCHED 
   THEN INSERT (ID, ApplicationType) 
           VALUES (ID, ApplicationType);
onedaywhen
How is this performance wise Vs the above method?
madlan
@madlan: In theory MERGE can be better optimized because it only needs to perform one pass. As ever with performance, it depends on many factors. See: Optimizing MERGE Statement Performance (http://technet.microsoft.com/en-us/library/cc879317.aspx).
onedaywhen