日期:2013-11-19  浏览次数:20502 次


这里只打算讲解四部分了,也就最简单、最常用的四部分。

  1、触发器。

     定义: 何为触发器?在SQL Server里面也就是对某一个表的一定的操作,触发某种条件,从而执行的一段程序。触发器是一个特殊的存储过程。
     常见的触发器有三种:分别使用于Insert , Update , Delete 事件。(SQL Server 2000定义了新的触发器,这里不提)

     我为什么要使用触发器?比如,这么两个表:

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

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

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

    这时候可以用到触发器。对于1,创建一个Update触发器:

    Create Trigger truStudent
      On Student
      for Update
    As
      if Update(StudentID)
      begin

        Update BorrowRecord 
          Set StudentID=i.StudentID
          From BorrowRecord br , Deleted  d ,Inserted i 
          Where br.StudentID=d.StudentID

      end       
                
    理解触发器里面的两个临时的表:Deleted , Inserted 。留意Deleted 与Inserted分别表示触发事件的表“旧的一条记录”和“新的一条记录”。
    一个Update 的过程可以看作为:生成新的记录到Inserted表,复制旧的记录到Deleted表,然后删除Student记录并写入新纪录。

    对于2,创建一个Delete触发器
    Create trigger trdStudent
      On Student
      for Delete
    As
      Delete BorrowRecord 
        From BorrowRecord br , Delted d
        Where br.StudentID=d.StudentID

    从这两个例子我们可以看到了触发器的关键:A.2个临时的表;B.触发机制。
    这里我们只讲解最简单的触发器。复杂的容后说明。
    理想上,我不鼓励使用触发器。触发器的初始设计思想,曾经被̶