Sql Server數據庫觸發器和存儲過程實例講解

關鍵詞:

觸發器

     定義: 何爲觸發器?在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                        --在Student表中創建觸發器
      for Update                         --爲什麼事件觸發
    As                                       --事件觸發後所要做的事情
      if Update(StudentID)          
      begin

        Update BorrowRecord
          Set StudentID=i.StudentID
          From BorrowRecord br , Deleted  d ,Inserted i     --Deleted和Inserted臨時表
          Where br.StudentID=d.StudentID

      end      
               
    理解觸發器裏面的兩個臨時的表:Deleted , Inserted 。注意Deleted 與Inserted分別表示觸發事件的表“舊的一條記錄”和“新的一條記錄”。

    一個數據庫系統中有兩個虛擬表用於存儲在表中記錄改動的信息,分別是:
                            虛擬表Inserted                    虛擬表Deleted

在表記錄新增時    存放新增的記錄                        不存儲記錄
        修改時          存放用來更新的新記錄                  存放更新前的記錄
        刪除時          不存儲記錄                            存放被刪除的記錄


    一個Update 的過程可以看作爲:生成新的記錄到Inserted表,複製舊的記錄到Deleted表,然後刪除Student記錄並寫入新紀錄。

    對於2,創建一個Delete觸發器
    Create trigger trdStudent
      On Student
      for Delete
    As
      Delete BorrowRecord
        From BorrowRecord br , Deleted d
        Where br.StudentID=d.StudentID

    從這兩個例子我們可以看到了觸發器的關鍵:A.2個臨時的表;B.觸發機制。
    這裏我們只講解最簡單的觸發器。複雜的容後說明。
    事實上,我不鼓勵使用觸發器。觸發器的初始設計思想,已經被“級聯”所替代

 

CREATE PROCEDURE UpdateSectionName
AS
BEGIN

--聲明一個遊標
DECLARE MyCURSOR CURSOR FOR
SELECT serial,[name] FROM dot

--打開遊標
open MyCURSOR

--聲明兩個變量
declare @serial int
declare @Name nvarchar(60)

--循環移動
fetch next from MyCURSOR into @serial,@Name
while(@@fetch_status=0)
begin
    update section set Name1=(select [name] from dot where serial=@serial) where serial1=@serial

  

   update section set Name2=(select [name] from dot where serial=@serial) where serial2=@serial

    fetch next from MyCURSOR into @serial,@Name
end

close MyCURSOR
deallocate MyCURSOR

END

EXEC  UpdateSectionName

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章