1

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?

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.