sql批量更新
1.业务需求
如下:
前台传给我一个 documentId和List<UpdateDocumentAnswer> 对象给我。
执行条件:通过这个documentId和List<UpdateDocumentAnswer>中对UpdateDocumentAnswer.id,修改document_answer表的数据。
简单说:就是希望通过一条update语句,根据不同的条件改变多条需要改变的数据。

update 表名 set
列1=
case
when 条件1 then 值1
when 条件2 then 值2 end,
列2=
case
when 条件1 then 值1
when 条件2 then 值2 end,
where 条件
解释:
我们要 修改列1, 当when 条件1 满足时,则将 列1 修改为 then 后面跟着的 值1,when 条件2 满足,则将列1修改为then 后面跟着的值2。
<update id="patchByDocumentId"> update document_answer <set> <trim prefix="template_question_id = case" suffix="end,"> <foreach collection="answers" item="answer"> <if test="answer.templateQuestionId != null"> when id=#{answer.id} then #{answer.templateQuestionId} </if> </foreach> </trim> <trim prefix="answer = case" suffix="end,"> <foreach collection="answers" item="answer"> <if test="answer.answer != null"> when id=#{answer.id} then #{answer.answer} </if> </foreach> </trim> <trim prefix="comments = case" suffix="end,"> <foreach collection="answers" item="answer"> <if test="answer.comments != null"> when id=#{answer.id} then #{answer.comments} </if> </foreach> </trim> </set> <where> document_id=#{documentId} <if test="answers != null"> and id in <foreach collection="answers" separator="," item="answer" open="(" close=")"> #{answer.id} </foreach> </if> </where> </update>
生成的sql日志:
update document_answer SET template_question_id = case when id=? then ? when id=? then ? end, answer = case when id=? then ? when id=? then ? end, comments = case when id=? then ? when id=? then ? end WHERE document_id=? and id in ( ? , ? )
换上我们想要的值:
update document_answer SET template_question_id = case when id=1 then 2 when id=1 then 3 end, answer = case when id=1 then '内容1' when id=2 then '内容2' end, comments = case when id=1 then '评论1' when id=2 then '评论2' end WHERE document_id=2 and id in ( 1 , 2 )

浙公网安备 33010602011771号