SQL点滴积累2--case when

项目中用到了case when 做判断条件分支进行更新表,犯了特别二的错误:以为case when 只操作符合条件的,不符合条件的不做操作,结果把本认为不更新的更新为默认值NULL了。如

需求:更新salary表中salary字段的值>5000的降低0.1

表salary数据如下

若更新语句为update  salary set salary=case when salary>5000 then salary*0.9 end

更新结果为,所有salary小于等于5000的全为null。结果明显不符合要求,只因为错用了case when 。

注意一点,ELSE是必需的,要是没有,不符合条件的将全部被更新为NUll。在Case函数中Else部分的默认值是NULL。

原文地址:https://www.cnblogs.com/mifeng/p/3205557.html