Share via

How to do the on duplicate update in insert query in sql

Arutprakasam 261 Reputation points
2023-11-29T10:18:41.71+00:00

Hi @everyone,

Please share your knowledge to do the on duplicate update in sql.

Developer technologies | Transact-SQL
Developer technologies | Transact-SQL

A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.

SQL Server | Other

2 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 83,816 Reputation points
    2023-11-29T22:37:05.1266667+00:00

    use the merge statement

    merge MyTable t
    using (select @col1, @col2) as s (col1, col2)
      on t.col2 = s.col2
    when matched then 
      update set col1 = s.col1
    when not matched then
      insert (col1, col2)
      values (s.col1, s.col2) 
    
    0 comments No comments

  2. Arutprakasam 261 Reputation points
    2023-11-29T15:25:22.72+00:00

    Hi @Olaf Helper , My requirement is I have to insert some col1, col2. Out of this col2 is unique column. So already col2 having same value. So I want to update that value automatically while doing the insert.


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.