Sqlite 创建触发器

--创建班级表
create table class
(
     id integer primary key autoincrement, --班级编号   
     className nvarchar(50) --班级名称
);

--创建学生表
create table student
(
     id integer primary key autoincrement, --编号   
     stuName nvarchar(20),    --学生名称
    stuSex bit,    --性别
    stuAge integer ,     --年龄
    classId   --班级编号
);

--创建插入触发器 (创建学生时要触发插入触发器去判断是否存在该班级,存在插入成功,反之插入失败)
create trigger fk_Insert
before insert on student
for each row 
begin
     select raise(rollback,'还没有该班级') 
     where (select id from class where id = new.classId ) is null;    
end;

--创建更新触发器 (更新学生时要触发更新触发器去判断是否存在更新班级,存在更新成功,反之更新失败)
create trigger fk_Update
before update on student
for each row 
begin
     select raise(rollback,'还没有该班级')
     where (select id from class where id = new.classId)is null; 
end;

--创建删除触发器 (删除班级时,首先根据班级编号删除该班级学生)
create trigger fk_Delete
before delete on class
for each row
begin
      delete from student where classId = old.classId;
end ;


insert into class(className) values('s1t64');

insert into student(stuName,stuSex,stuAge,classId)values('zhangsan',1,23,1);

update student set stuName='lishi',classId=1 where id = 1;

select * from class ;
select * from student limit 0,100 ; -- 分页查询从索引0开始查找,100条数据

 

posted on 2014-05-17 00:00  IOTer  阅读(877)  评论(0编辑  收藏  举报

导航