MySQL存储过程在一定条件下更新记录?
为此,可以在PROCEDURE中将UPDATE命令与WHERE子句一起使用。让我们首先创建一个表-
mysql> create table DemoTable -> ( -> Id int, -> FirstName varchar(20), -> LastName varchar(20) -> );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable values(101,'David','Brown'); mysql> insert into DemoTable values(102,'Chris','Brown'); mysql> insert into DemoTable values(103,'John','Doe');
使用select语句显示表中的所有记录-
mysql> select *from DemoTable;
这将产生以下输出-
+------+-----------+----------+ | Id | FirstName | LastName | +------+-----------+----------+ | 101 | David | Brown | | 102 | Chris | Brown | | 103 | John | Doe | +------+-----------+----------+ 3 rows in set (0.00 sec)
这是创建存储过程的查询-
mysql> delimiter // mysql> create procedure update_sp(fName varchar(20),lName varchar(20)) -> begin -> update DemoTable -> set FirstName=fName, -> LastName=lName -> where Id=101; -> end -> // mysql> delimiter ;
现在您可以使用调用命令来调用存储过程-
mysql> call update_sp('Adam','Smith');
让我们再次检查表记录-
mysql> select *from DemoTable;
这将产生以下输出-
+------+-----------+----------+ | Id | FirstName | LastName | +------+-----------+----------+ | 101 | Adam | Smith | | 102 | Chris | Brown | | 103 | John | Doe | +------+-----------+----------+ 3 rows in set (0.00 sec)