sql語句中如何根據字段在列表中的情況執行更新操作
在進行批量更新時,需要根據待更新數據的字段列表逐個字段進行判斷更新,此時的判斷條件就是該字段是否在這個列表中。sql語句中,可以通過if語句來實現這種判斷。
如果使用Java代碼,dao層方法可以定義為:
int batchupdatebyid( @param("entitylist") list<schooldo> entitylist, @param("fieldnameslist") list<string> fieldnameslist);
登錄后復制
相應的xml文件可以編寫為:
<!-- 批量插入 --> <update id="batchUpdateById"> <foreach collection="entityList" item="entity" index="index1" open="(" close=")" separator=";"> UPDATE school_info SET <if test='fieldNamesList.contains("schoolNo")'> schoolNo = #{entity.getSchoolNo} </if> <if test='fieldNamesList.contains("schoolRank")'> schoolRank = #{entity.getSchoolRank} </if> where dataId = #{entity.dataId} </foreach> </update>
登錄后復制
在這個xml文件中,fieldnameslist是包含待更新字段的列表。通過if語句,執行判斷條件fieldnameslist.contains(“字段名”),如果為真,則更新該字段。