我有一个整数列表,我希望(批量)插入带有单个整数列的SQL Server表。
问题是表中插入的某些值可能已经存在。有没有办法在Sql Server和MyBatis中执行批量“插入如果丢失”?
答案 0 :(得分:1)
以下映射器为我工作:
<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>