資料庫觸發器

2021-09-30 11:47:37 字數 2792 閱讀 3426

修改操作           inserted表            deleted表

增加insert        存放新增的記錄          -------

刪除delete          ---------           存放被刪除的記錄

修改update        存放更新後的記錄      存放更新前的記錄

使用游標,刪除乙個表的內容,把符合條件的內容增加到另外乙個表

create trigger tg_test0

on  t_stu

after delete

as begin

declare @name varchar(50)

declare cur cursor

for select sname from deleted

open cur

while @@fetch_status=0

begin

fetch next from cur into @name

insert into t_outstu values(@name)

endclose cur

deallocate cur

endgo

更新乙個表的某一項資料,把另外乙個表的這個資料也更新

set ansi_nulls on

set quoted_identifier on

goalter trigger [dbo].[tg_teg]

on  [dbo].[t_card]

after update

as begin

declare @no int

select @no=no from inserted--更新後的值

declare @nn int

select @nn=no from deleted--更新前的值

update t_borrow set no=@no where no=@nn

endinstead of 觸發器的使用(原操作語句被替換)

lter trigger [dbo].[tg_test]

on  [dbo].[t_card]

instead of delete

as begin

declare @n int

declare @m int

select @n=no from deleted

select @m=count(*) from t_borrow where no=@n

if(@m=0)

begin

delete from t_card where no=@n

endelse

begin

select '存在借書記錄不能刪除'

endend

觸發器alter trigger [dbo].[t_t1]

on  [dbo].[t_class]

after  update

as begin

declare @oldcid int

declare @name varchar(50)

select @name=cname ,@oldcid=cid from deleted

declare @nename varchar(50)

select @nename=cid from t_class where

cname= @nename

update t_stu set cid=@nename  where cid=@oldcid

set nocount on;

endalter trigger [dbo].[tg_1]

on  [dbo].[t_class]

after update

as begin

declare @n int

declare @m int

select @n=cid from deleted

select @m=cid from inserted

update t_stu set cid=@m where cid=@n

endalter trigger [dbo].[tg_class]

on  [dbo].[t_class]

after delete

as begin

set nocount on;

select * from t_class

endalter trigger [dbo].[tg_classid]

on  [dbo].[t_class]

after update

as begin

declare @id int

select @id=cid from inserted

update t_stu set cid=@id

where cid in

(select cid from deleted)

endalter trigger [dbo].[tg_delclass]

on  [dbo].[t_class]

instead of  delete

as begin

declare @id int

select @id=cid from deleted

if exists(select * from t_stu where cid=@id)

begin

select '當前班級存在學生,不能刪除'

endelse

begin

delete from t_class where cid=@id

endend

資料庫觸發器

觸發器是一種特殊型別的儲存過程,它不同於我們前面介紹過的儲存過程。觸發器主要是通過事件進行觸發而被執行的,而儲存過程可以通過儲存過程名字而 被直接呼叫。當對某一表進行諸如update insert delete 這些操作時,sql server 就會自動執行觸發器所定義的sql 語句,從而確保對資料...

資料庫觸發器

最近做了個觸發器的例子 create trigger tru user on user for update asif update status begin update user set stopflag 1 from inserted where user.userid inserted.us...

資料庫 觸發器

觸發器的概念 是使用者定義在關係表上的一類有事件驅動的特殊過程。一旦定義,任何對錶的增刪改操作均有伺服器自動啟用相應的觸發器,在dbms核心層進行集中的完整性控制。類似於約束,但比約束更靈活。觸發器的分類 dml觸發器 dml data manipulation language 觸發器是當資料庫伺...