SQL Server ——觸發器

來源:互聯網
上載者:User

標籤:

觸發器是一類特殊的預存程序,在對錶UPDATE、INSERT或DELETE語句時自動執行。

例題1.

--例題1.利用觸發器顯示‘改變了一條資料’use mydb gocreate trigger tr_info_add on infofor insert,deleteasprint ‘改變了一條資料‘go

例題2.

例題3.

--例題3:水果表改變numbers列時,向orderdetails表中添加資料水果編號,數量變化。go create trigger tr_fruit_buy2 on fruitfor update, insert ,deleteas--操作之前列的資料declare @num1 intselect @num1=numbers from deleted--操作之後的資料declare @num2 intselect @num2=numbers from inserted--資料差declare @num intset @num=@num1-@num2--從deleted表中取出水果編號declare @code varchar(50)select @code=ids from deleted--將資料差、水果編號輸入orderdetails表insert into orderdetails (ordercode,[count]) values (@code,@num)goselect * from Fruit select * from OrderDetails --添加觸發器,執行以下語句,觸發兩個觸發器tr_fruitbuy和tr_fruit_buy2結果如下update Fruit set numbers=numbers-5 where Ids =‘k002‘select * from OrderDetails

例題4

--例題:instead of觸發器,刪除info表的資料時,先刪除work和family的資料,再刪info相應的資料select * from Info select * from Work select * from Family gocreate trigger tr_person_deletet on infoinstead of deleteas--刪除work相關資料      --取出需要的delete資訊declare @code varchar(50)select @code=code from deleted      --刪除delete from Work where InfoCode =@code --刪除family相關資料delete from Family where InfoCode =@code --最後刪除info表中的相關資料(info表是family表和work表的主表,最後才能執行刪除)delete from info where code=@codego--添加觸發器後執行刪除delete from Info where Code =‘p002‘

SQL Server ——觸發器

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.