mysql触发器和存储过程小测试

 

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 i<count do

insert 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;

mysql触发器和存储过程小测试

你可能感兴趣的:(mysql,trigger,procedure)