Mybatis中case when 配合 trim的使用方法
Mybatis中trim标签的使用
case when的使用方法
demo(批量更新数据)
Mybatis中trim标签的使用
1、作用:一般用于去除sql语句中多余的and关键字、逗号、或者给sql语句前拼接where、set以及values等前缀或后缀
2、属性:
属性 描述
prefix 给sql语句拼接的前缀
suffix 给sql语句拼接的后缀
prefixOverrides 去除sql语句前面的关键字或者字符,该关键字或者字符由prefixOverrides属性指定,假设该属性指定为"AND",当sql语句的开头为"AND",trim标签将会去除该"AND"
suffixOverrides 去除sql语句后面的关键字或者字符,该关键字或者字符由suffixOverrides属性指定
case when的使用方法
1、简单函数:
CASE expression
WHEN condition1 THEN result1
WHEN condition2 THEN result2
...
ELSE result
END
2、搜索函数
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
...
ELSE result
END
总结: CASE 表示函数开始,END 表示函数结束。如果 condition1 成立,则返回 result1, 如果 condition2 成立,则返回result2,当全部不成立则返回else后面的 result,而当有一个成立之后,后面的就不执行了。
demo(批量更新数据)
(批量更新t_cusomer表中的数据,前提批量数据以放入集合中)
<update parameterType="">
1
update t_customer
1
<trim prefix="set" suffixOverrides=",">
<!-- 拼接case when 这是一种写法 -->
<foreach collection="list" separator="" item="cus" open="c_age = case id" close="end, ">
when #{} then #{}
</foreach>
<!-- 拼接case when 这是另一种写法,这种写着更专业的感觉 -->
<trim prefix="c_name =case" suffix="end,">
<foreach collection="list" item="cus">
<if test="!=null">
when id=#{} then #{}
</if>
</foreach>
</trim>
</trim>
</update>
两种不同写法的语句,实际输出代码:
1)set c_age=case id when #{} then {} end
2)set c_name=case when id=#{} then #{} end
————————————————
版权声明:本文为****博主「南信院二年级三班优秀数学课代表加三好学生」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:/wohainengqiao/article/details/107831359