If Exists Update Else Insert with VB.net (sql parameterised query)

前端 未结 3 1110
灰色年华
灰色年华 2021-01-22 15:55

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

UPDATE [Application_Type_Table] 
SET ApplicationType=\'Test Va         


        
相关标签:
3条回答
  • 2021-01-22 16:29
    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"
    
    0 讨论(0)
  • 2021-01-22 16:32

    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 ;)

    0 讨论(0)
  • 2021-01-22 16:33

    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);
    
    0 讨论(0)
提交回复
热议问题