zoukankan      html  css  js  c++  java
  • 触发器练习一

    有两个表,学生表和借书表。 用到的功能有
            1.如果我更改了学生的学号,我希望他的借书记录仍然与这个学生相关(也就是同时更改借书记录表的学号); 
            2.如果该学生已经毕业,我希望删除他的学号的同时,也删除它的借书记录。 
        

    创建学生表:

    Create Table Student(              --学生表 
            StudentID int primary key,       --学号
           )

    创建借书表:

     Create Table BorrowRecord(               --学生借书记录表 
            BorrowRecord   int identity(1,1),       --流水号   
                                StudentID      int ,                    --学号 
            BorrowDate     datetime,                --借出时间 
            ReturnDAte     Datetime,                --归还时间 
          )

    创建触发器一:要求如果我更改了学生的学号,我希望他的借书记录仍然与这个学生相关(也就是同时更改借书记录表的学号);
    分析:1.触发器要建在学生表,因为是学生表的学号变了导致借书表的学号也改变。

        2.需要用到关联关系,这里就需要用到系统的两个临时表。

    理解触发器里面的两个临时的表:Deleted , Inserted 。注意Deleted Inserted分别表示触发事件的表旧的一条记录新的一条记录。 
         一个数据库系统中有两个虚拟表用于存储在表中记录改动的信息,分别是: 
             虚拟表Inserted                     虚拟表Deleted 

    在表记录新增时  存放新增的记录                         不存储记录 
            修改时存放用来更新的新记录     存放更新前的记录 
            删除时不存储记录                       存放被删除的记录

    创建触发器 T_student_insert

    create trigger t_student_insert

    after insert

    as

    if update(StudentID)

    begin

      update BorrowRecord set StudentID=i.StudentID from BorrowEecord r,deleted d,inserted i where r.StudentID=d.StudentID

    end

    创建触发器二:要求如果该学生已经毕业,我希望删除他的学号的同时,也删除它的借书记录。

    create trigger t_student_delete

    after delete

    as

    begin

    delete BorrowRecord from deleted d,BorrowRecord b where b.StudentID=d.StudentID

  • 相关阅读:
    System.Web.Mvc.HttpPostAttribute vs System.Web.Http.HttpPostAttribute? [duplicate]
    Autofac Exception Summary Autofac异常汇总
    AppBox v1.0 发布了
    [原创]ExtAspNet秘密花园(十一) — 布局概述
    ExtAspNet v3.1.9
    ExtAspNet v3.1.8 发布了
    ExtAspNet 主题赏析 7款 超炫!
    ExtAspNet v3.1.7
    ExtAspNet v3.1.6
    [原创]采用Asp.Net的Forms身份验证时,持久Cookie的过期时间会自动扩展
  • 原文地址:https://www.cnblogs.com/cuig/p/7873849.html
Copyright © 2011-2022 走看看