
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Avoid Variable Value Change in MySQL Stored Procedure
We will create a stored procedure that does not change the variable value whenever the value is updated.
Let us first create a table −
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, Value int ); Query OK, 0 rows affected (0.63 sec)
Insert some records in the table using insert command −
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;
Output
+----+-------+ | Id | Value | +----+-------+ | 1 | 100 | +----+-------+ 1 row in set (0.00 sec)
Following is the stored procedure that shows the old value after updating −
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 ;
Now you can call the stored procedure using CALL command −
mysql> call updateValue100();
Output
+-------------------------------------------------------+ | @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)
Advertisements