I have a list of Integers which I want to (batch) insert into an SQL Server table with a single integer column.
The problem is that some of the values being inserted might already exist in the table. Is there a way of performing a batch "insert if missing" into Sql Server and MyBatis?
The following mapper worked for me :
<insert id="batchAddIntegers" parameterType="java.util.List">
DECLARE @ValuesToInsertTempTable TABLE (ColumnName integer)
DECLARE @UpdateVariable integer
SET NOCOUNT ON
INSERT INTO @ValuesToInsertTempTable (ColumnName) VALUES
<foreach item="item" index="index" collection="list" open="(" separator="),(" close=")">
#{item}
</foreach>
SET NOCOUNT OFF
MERGE TargetTable
USING @ValuesToInsertTempTable AS S
ON TargetTable.ColumnName=S.ColumnName
WHEN NOT MATCHED THEN
INSERT (ColumnName) VALUES (S.ColumnName)
WHEN MATCHED THEN
UPDATE SET @UpdateVariable = @UpdateVariable + 1;
</insert>
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.