mysql觸發器和存儲過程小測試
1. 為了測試觸發器和存儲過程,首先建立一張簡單的表:
www.2cto.com
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;