执行sql server insert但如果找到重复,则执行更新

时间:2015-03-19 10:37:27

标签: mysql sql-server jdbc

我有很多记录,我想使用MYSQLMSSQLJDBC中触发批量插入查询:

我的查询是:INSERT INTO dentalitems SET itemID = ?, categoryid = ?, treatmentAreaID = ?, paintTypeID=?, procedurecode=? ON DUPLICATE KEY UPDATE itemID = ?, procedurecode = ?

上面的查询适用于MYSQL - 它会将记录插入表中,但如果有重复的密钥则会执行更新。

我的问题是我想在SQL Server中执行相同的上述操作,但上面的查询仅适用于MYSQL。我搜索了一个SQL Server查询,但我没有找到任何查询。

在我的表itemIDprocedurecode中是唯一的列。

如何使用MSSQL Server做同样的事情?

1 个答案:

答案 0 :(得分:0)

试试这个。 表位置(LocationId INT PrimaryKey,LocationName VARCHAR)

MERGE dbo.Location AS target
USING (SELECT 100, 'Location Name') AS source (Id, Name)
    ON (target.LocationId = source.Id)
WHEN MATCHED THEN UPDATE SET LocationName = source.Name
WHEN NOT MATCHED THEN INSERT (LocationId, LocationName) VALUES (source.Id, source.Name);

- >

MERGE dbo.Location AS target
USING (SELECT AId, AName FROM A) AS source (Id, Name)
    ON (target.LocationId = source.Id)
WHEN MATCHED THEN UPDATE SET LocationName = source.Name
WHEN NOT MATCHED THEN INSERT (LocationId, LocationName) VALUES (source.Id, source.Name);