Home > Database > Mysql Tutorial > body text

如何测试mysql触发器和存储过程_MySQL

WBOY
Release: 2016-06-01 13:23:20
Original
923 people have browsed it

bitsCN.com 1. 为了测试触发器和存储过程,首先建立一张简单的表:

CREATE TABLE `airuser` (
`userId` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(128) NOT NULL,
PRIMARY KEY (`userId`)
)ENGINE=InnoDB DEFAULT CHARSET=utf8

2. 为该表的插入操作,创建一张记录表:

CREATE TABLE `airuser_record` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(45) DEFAULT NULL,
`edittime` timestamp NULL DEFAULT NULL,
`edittype` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

3. 编写一个插入操作的触发器:

DROP TRIGGER insert_trigger;
delimiter |
CREATE TRIGGER insert_trigger BEFORE INSERT ON airuser
FOR EACH ROW BEGIN
INSERT INTO airuser_record SET username = NEW.username, edittime=now(), edittype='insert';
END;

SHOW TRIGGERS;

4. 为批量插入编写存储过程:

DROP procedure createUsers;
delimiter |
create procedure createUsers(IN count int)
begin
declare i int;
set i=0;
while iinsert into airuser set username=concat('user_',i);
set i=i+1;
end while;
end;

show procedure status;

5. 调用存储过程,验证存储过程是工作的,并验证在插入记录前,触发器能正确被触发:

call createUsers(10);

6. 最后通过插入记录表再次验证:

SELECT * FROM mars_jpa.airuser_record;
bitsCN.com

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template