mybatis中使用sql @变量

SQL语句定义变量,如下:

SET @c = '2333';-- 定义变量并赋值
 
SELECT @c;-- 查询定义的变量的值

执行结果

2333

那么如何在mybatis的框架实现变量的定义的呢?如果能实现变量的定义,那就可以在mybatis上写一定量的业务代码,也是不错的!

一、变量的定义及使用

<update id="updatePrice">
    /*1.变量定义*/
    select @isEnd:=0,@isFinish:=1;
    /*2.使用变量*/
    update Sc_Stock a set a.cost_price = 10 where @isFinish= 1 and @isEnd = 0;
</update>


二、变量的赋值

<update id="updatePrice">
    /*1.变量定义*/
    select @newPrice:=0;
    /*2.变量赋值*/
    update Sc_Stock a set a.price = @newPrice := 11 where a.id = 2222;
    /*3.变量使用*/
    update Sc_Stock a set a.num = 2 where @newPrice = 11;
</update>


三、变量使用小技巧

<update id="updatePrice">
    /*1.变量定义*/
    select @isFinish:=0;
    /*2.变量使用*/
    update Sc_Stock set num = 2 where newPrice = 11 and if(@isFinish = 0, 0, @isFinish := a.is_finish);
</update>

解释一下:上方更新语句最后会变成

update Sc_Stock  set num = 2 where newPrice = 11 and 0;

或是

update Sc_Stock  set num = 2 where newPrice = 11 and 1;
发布了738 篇原创文章 · 获赞 337 · 访问量 77万+

猜你喜欢

转载自blog.csdn.net/a772304419/article/details/103952701
今日推荐