SQL Server 触发器demo

时间:2022-02-16 03:04:09

 

GO

/****** Object: Trigger [dbo].[tri_device] Script Date: 2018/6/11 10:56:08 ******/

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

 

Create trigger [dbo].[tri_device]

on [dbo].[Device]

for insert,update,delete

as

begin

/*

* 插入操作

*/

if EXISTS(SELECT 1 FROM inserted) AND NOT EXISTS(SELECT 1 FROM deleted)

insert into RealData(DtuId,Val,RcvTime)

select DtuId,'0',getdate() from inserted;

/*

*更新操作

*/

IF EXISTS(SELECT 1 FROM inserted) AND EXISTS(SELECT 1 FROM deleted)

update RealData set DtuId=a.DtuId from inserted a

/*

*删除操作

*/

IF NOT EXISTS(SELECT 1 FROM inserted) AND EXISTS(SELECT 1 FROM deleted)

delete from RealData where DtuId=(select a.DtuId from deleted a)

end;