T-SQL - Using Trigger to monitor DML changes

1. Log table

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[HotelOrder_OrderStatus_Log]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[HotelOrder_OrderStatus_Log](
[OrderStatusLogID] [int] IDENTITY(1,1) NOT NULL,
[AppName] [nvarchar](50) NOT NULL,
[EventInfo] [nvarchar](max) NOT NULL,
[SystemUser] [nvarchar](50) NOT NULL,
[HostName] [nvarchar](50) NOT NULL,
[TableName] [nvarchar](50) NOT NULL,
[RunTime] [datetime] NOT NULL
CONSTRAINT [PK__HotelOrder_OrderStatus_Log] PRIMARY KEY CLUSTERED
(
[OrderStatusLogID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
END
go

2. Trigger HotelOrder

IF NOT EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[CKHotelOrderupdateItem]'))
EXEC dbo.sp_executesql @statement = N'

CREATE trigger [dbo].[CKHotelOrderupdateItem] on [dbo].[HotelOrder]
for update
as
if update( OrderStatus ) and
( select top 1 createtime from inserted ) begin

set nocount on

declare @temp table ( EventType varchar(50), [Parameters] int ,EventInfo varchar(6000) )
declare @spid varchar(20)

set @spid = cast( @@spid as varchar )
insert @temp exec( ''DBCC INPUTBUFFER (''+ @spid +'')'' )

insert into [HotelOrder_OrderStatus_Log]
select App_Name(), EventInfo, SYSTEM_USER, Host_name(), ''HotelOrder'', getdate() from @temp
end'
go

3. Trigger HotelOrderDetail

IF NOT EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[CKHotelOrderDetailupdateItem]'))
EXEC dbo.sp_executesql @statement = N'

CREATE trigger [dbo].[CKHotelOrderDetailupdateItem] on [dbo].[HotelOrderDetail]
for update
as
if ( update( CheckInStatus ) or update( CheckOutStatus ) ) and
( select top 1 createtime from inserted ) begin

set nocount on

declare @temp table ( EventType varchar(50), [Parameters] int ,EventInfo varchar(6000) )
declare @spid varchar(20)

set @spid = cast( @@spid as varchar )
insert @temp exec( ''DBCC INPUTBUFFER (''+ @spid +'')'' )

insert into [HotelOrder_OrderStatus_Log]
select App_Name(), EventInfo, SYSTEM_USER, Host_name(), ''HotelOrderDetail'', getdate() from @temp
end'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值