前言
本人呢,由于懒得下载sql server.本想用mysql一直代替学校老师教的sql server.一直用的风生水起,洋洋得意.直到那天…遇到了触发器!!!什么?这玩意这么恐怖?那是,这玩意让我用mysql花了3天…这里多谢@noisyfox 网友的指点.在这里我应该叫他前辈!
提示:以下是本篇文章正文内容,下面案例可供参考
题目要求:创建触发器要求在插入和更新学生年龄时检查age是否在15到60之间,如不在15到60,则弹出“年龄不合法”提示信息;
一、sql server触发器示例
sql server临时表
create trigger stu_insert
on stu
for insert
as
declare @age char(10)
select @age=age from inserted
if (@age<16 or @age>60)
begin
print '年龄不合法'
rollback TRANSACTION
end
else
print '年龄合法插入成功'
Drop trigger stu_insert;
commit;
create trigger stu_delete
on stu
for delete
as
insert into stu1(sno,name,age,class)
select sno,name,age,class from deleted
if @@error!=0
begin
print '备份失败'
rollback
end
else
print '备份成功'
二、mysql触发器对应的示例
关于mysql不支持显示或隐式的提交
mysql如何避免显示或隐式的提交
for each row解释
delimiter $$
create trigger stu_insert
before insert
on stu
for EACH ROW
BEGIN
if (new.age < 16 or new.age > 60) then
SIGNAL SQLSTATE '02000' SET MESSAGE_TEXT = 'Warning: 年龄不合法!';
else
select '年龄合法插入成功' into @str2;
end if;
end
$$
delimiter ;
commit;
Drop trigger stu_insert;
commit;
create trigger stu_delete
after delete
on stu
for EACH ROW
BEGIN
insert into stu1(sno, name, age, class) values(now(),now(),now(),now());
if @error != 0 then
SIGNAL SQLSTATE '02000' SET MESSAGE_TEXT = 'Warning: 备份失败!';
else
select '备份成功' into @str2;
end if;
end;
commit;
|