数据库触发器inserted和deleted详解
生活随笔
收集整理的這篇文章主要介紹了
数据库触发器inserted和deleted详解
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
createtriggerupdateDeleteTime
onuser
forupdate
as
begin
updateusersetUpdateTime=(getdate())fromuserinnerjoininsertedonuser.UID=Inserted.UID
end
上面的例子是在執行更新操作的時候同時更新,一下修改時間。
關鍵在于Inserted表
觸發器語句中使用了兩種特殊的表:deleted表和inserted表。
Deleted 表用于存儲 DELETE 和 UPDATE 語句所影響的行的復本。在執行 DELETE 或 UPDATE 語句時,行從觸發器表中刪除,并傳輸到 deleted 表中。Deleted 表和觸發器表通常沒有相同的行。
Inserted 表用于存儲 INSERT 和 UPDATE 語句所影響的行的副本。在一個插入或更新事務處理中,新建行被同時添加到 inserted 表和觸發器表中。Inserted 表中的行是觸發器表中新行的副本。
1.插入操作(Insert)
Inserted表有數據,Deleted表無數據
2.刪除操作(Delete)
Inserted表無數據,Deleted表有數據
3.更新操作(Update)
Inserted表有數據(新數據),Deleted表有數據(舊數據)
應用實例
Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
-- =============================================
-- Author: <Author,sufei>
-- Create date: <Create Date,2010-05-11>
-- Description: <當是短信充值時修改相信的記錄使記錄不會重復獲取>
-- =============================================
ALTER TRIGGER [dbo].[updatestart]
ON [dbo].[OrderTelecom] FOR update
AS
BEGIN
DECLARE @state int;
DECLARE @note2 varchar(50)
SELECT @state= Inserted.ortState,@note2 =Inserted.ortNote2 from Inserted
IF @state=1 AND @note2=1
begin
--當發短信貓取走記錄時修改狀態為成功和取過的狀態
update OrderTelecom set OrderTelecom.ortState=2 ,OrderTelecom.ortSmsmessages='短信充值成功'
from OrderTelecom inner join Inserted on OrderTelecom.ortId=Inserted.ortId
end
if @state in(2,3,10) and @note2=0
begin
update OrderTelecom set ortNote2=1
from OrderTelecom inner join Inserted on OrderTelecom.ortId=Inserted.ortId
end
END
總結
以上是生活随笔為你收集整理的数据库触发器inserted和deleted详解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: luogu-单调队列/单调栈专题
- 下一篇: 田忌能赢的前提是什么?