USE [AdventureWorks2014]
GO
IF NOT EXISTS (SELECT 1 FROM sys.sysobjects WHERE id=object_id(N'[dbo].[TEST]') AND OBJECTPROPERTY(id, N'IsTable')=1 )
BEGIN
CREATE TABLE [dbo].[TEST](
[OBJECT_ID] [INT] NOT NULL,
[NAME] [VARCHAR](8) NULL,
CONSTRAINT PK_TEST PRIMARY KEY (OBJECT_ID)
)
END
GO
INSERT INTO dbo.TEST
SELECT 1, 'kerry' UNION ALL
SELECT 2, 'jimmy'
ALTER TABLE TEST ADD [HOST_NAME] NVARCHAR(256)
ALTER TABLE TEST ADD [PROGRAM_NAME] NVARCHAR(256);
ALTER TABLE TEST ADD LOGIN_NAME NVARCHAR(256);
CREATE TRIGGER TRG_TEST ON dbo.TEST AFTER
INSERT,UPDATE
AS
IF (EXISTS(SELECT 1 FROM INSERTED))
BEGIN
UPDATE dbo.TEST
SET dbo.TEST.[HOST_NAME] = ( SELECT host_name
FROM sys.dm_exec_sessions
WHERE session_id = @@SPID
) ,
dbo.TEST.PROGRAM_NAME = ( SELECT program_name
FROM sys.dm_exec_sessions
WHERE session_id = @@SPID
) ,
dbo.TEST.LOGIN_NAME = ( SELECT login_name
FROM sys.dm_exec_sessions
WHERE session_id = @@SPID
)
FROM dbo.TEST t
INNER JOIN INSERTED i ON t.OBJECT_ID = i.OBJECT_ID
END
GO
接下来,我们来简单测试一下,如下所示,分布插入、更新一条记录
INSERT INTO dbo.TEST(OBJECT_ID,NAME)
SELECT 3,'ken'
UPDATE dbo.TEST SET NAME='Richard' WHERE OBJECT_ID=2;
如下所示,因为我只是用SSMS更新,插入数据,所以捕获的是Microsoft SQL Server Management Studio - Query。
USE [AdventureWorks2014]
GO
DROP TABLE dbo.[TRG_TEST_SESSION_INFO];
GO
IF NOT EXISTS (SELECT 1 FROM sys.sysobjects WHERE id=object_id(N'[dbo].[TRG_TEST_SESSION_INFO]') AND OBJECTPROPERTY(id, N'IsTable')=1 )
BEGIN
CREATE TABLE [TRG_TEST_SESSION_INFO](
[ID] INT NOT NULL IDENTITY(1,1),
[OBJECT_ID] INT,
[HOST_NAME] NVARCHAR(256),
[PROGRAM_NAME] NVARCHAR(256),
[LOGIN_NAME] NVARCHAR(256),
CONSTRAINT PK_TRG_TEST_SESSION_INFO PRIMARY KEY (ID)
)
END
GO
CREATE TRIGGER TRG_TEST_SESSION ON dbo.TEST
AFTER INSERT ,UPDATE
AS
IF (EXISTS(SELECT 1 FROM INSERTED))
BEGIN
/*
INSERT INTO dbo.[TRG_TEST_SESSION_INFO]
SELECT (SELECT I.OBJECT_ID FROM INSERTED I), HOST_NAME,program_name,login_name
FROM sys.dm_exec_sessions
WHERE session_id = @@SPID*/
INSERT INTO dbo.[TRG_TEST_SESSION_INFO]
SELECT I.OBJECT_ID, S.HOST_NAME,S.PROGRAM_NAME,S.LOGIN_NAME
FROM sys.dm_exec_sessions s,
Inserted i
WHERE session_id = @@SPID
END
GO