Malt
Malt

Reputation: 30285

Batch "insert if missing" with SQL server and MyBatis

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?

Upvotes: 1

Views: 1649

Answers (1)

Malt
Malt

Reputation: 30285

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>

Upvotes: 1

Related Questions