如何在记录更新时避免 MySQL 存储过程中变量值发生变化?
我们将创建一个在每次更新值时都不会更改变量值的存储过程。
首先,让我们创建一个表 -
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, Value int ); Query OK, 0 rows affected (0.63 sec)
使用 insert 命令向表中插入一些记录 -
mysql> insert into DemoTable(Value) values(100); Query OK, 1 row affected (0.13 sec) Display all records from the table using select statement : mysql> select *from DemoTable;
输出
+----+-------+ | Id | Value | +----+-------+ | 1 | 100 | +----+-------+ 1 row in set (0.00 sec)
以下是更新后显示旧值的存储过程 -
mysql> DELIMITER // mysql> CREATE PROCEDURE updateValue100() BEGIN DECLARE myValue int; select @myValue :=(select Value from DemoTable where Id=1); select @myValue; update DemoTable set Value=200 where Id=1; select @myValue :=(select Value from DemoTable where Id=1); select @myValue; END // Query OK, 0 rows affected (0.21 sec) mysql> DELIMITER ;
现在,你可以使用 CALL 命令调用存储过程 -
mysql> call updateValue100();
输出
+-------------------------------------------------------+ | @myValue :=(select Value from DemoTable where Id=1) | +-------------------------------------------------------+ | 100 | +-------------------------------------------------------+ 1 row in set (0.00 sec) +----------+ | @myValue | +----------+ | 100 | +----------+ 1 row in set (0.01 sec) +-------------------------------------------------------+ | @myValue :=(select Value from DemoTable where Id=1) | +-------------------------------------------------------+ | 200 | +-------------------------------------------------------+ 1 row in set (0.16 sec) +----------+ | @myValue | +----------+ | 200 | +----------+ 1 row in set (0.17 sec) Query OK, 0 rows affected (0.18 sec)
广告