简体   繁体   中英

How to overwrite a record with same primary key in SQL Server?

I am using Python to push data to SQL Server. Suppose I have a table like below:

在此处输入图像描述

I am pushing the data using following code and query

query = """INSERT INTO TestTable (Key, One, Two) values(?,?,?)"""

Next, I want to push a Data with values 'A2', 'A3' in column 'Two' and two new rows like below:

在此处输入图像描述

I want to have a query with inserts new row if the primary key is not present and overwrite the row when the primary key is present. I tried using REPLACE INTO instead of INSERT INTO but that does not seem to work in SQL Server.

Please can you help.

Sql Server supports the MERGE statement for upserts.

And to upsert 1 tupple, VALUES can be used.

MERGE TestTable AS t
USING (VALUES (?,?,?)) AS s([Key], One, Two) 
ON (s.[Key] = t.[Key])
WHEN NOT MATCHED BY Target THEN
  INSERT ([Key], One, Two) 
  VALUES (s.[Key], s.One, s.Two) 
WHEN MATCHED THEN UPDATE SET
  One = s.One,
  Two = s.Two;

db<>fiddle here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM