如何避免 MySQL 存储过程中的变量值在记录更新时发生变化?
mysqlmysqli database
我们将创建一个存储过程,该过程在更新值时不会更改变量值。
首先我们创建一个表 −
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)