Total Pageviews

2019/03/12

[SQL Server] IF EXISTS update else insert

Scenario
If I would like to implement a SQL statement to fulfill the following requirement, how to do it?


How-To
You can utilize if exists..else to do, here has an example:
  IF EXISTS (select * from TEST where ID = :id)
    UPDATE TEST 
    SET USER_ID = :userId, 
 USER_NAME = :userName, 
 LAST_UPDATE_TIME = getdate() 
    WHERE ID = :id
  ELSE
    INSERT INTO TEST (ID, 
                      USER_ID, 
            USER_NAME, 
        CREATE_TIME, 
        LAST_UPDATE_TIME)
               VALUES (:id, 
         :userId, 
         :userName, 
         getdate(), 
         getdate())
  ;


No comments: