SQLSERVER Inserted和deleted詳解


create trigger updateDeleteTime
on user
for update
as
begin 
 update user set UpdateTime=(getdate()) from user inner join inserted on user.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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM