Sqlserver 触发器 记录删除 与修改
原创
©著作权归作者所有:来自51CTO博客作者朋克版小红帽的原创作品,请联系作者获取转载授权,否则将追究法律责任
最近项目里发生一些问题 发现数据无故被删除 只能作一个触发器来记录SQL
需要 一个触发器 一个log表
log表
CREATE TABLE [dbo].[LOGR](
[USERID] [varchar](50) NULL,
[STRSQL] [varchar](max) NULL,
[DATE] [varchar](8) NULL,
[TIME] [varchar](8) NULL,
[TABLNM] [nvarchar](50) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
触发器
CREATE TRIGGER [dbo].[KNMT_LOG] ON [dbo].[PATIENT]
FOR UPDATE, DELETE
AS
DECLARE @CLIENT AS VARCHAR(50)
DECLARE @DATE AS VARCHAR(8)
DECLARE @TIME AS VARCHAR(8)
DECLARE @USERNAME AS VARCHAR(50)
DECLARE @STATMT AS VARCHAR(max)
DECLARE @strSQL AS VARCHAR(100)
SET @CLIENT = HOST_NAME()
SET @DATE = CONVERT(VARCHAR(8),GETDATE(),112)
SET @TIME =REPLACE(CONVERT(VARCHAR(8),GETDATE(),108),':','')
SET @strSQL='DBCC INPUTBUFFER('+CAST(@@SPID AS VARCHAR(50))+')'
CREATE TABLE #STATEMENT (C1 VARCHAR(50),C2 VARCHAR(50),C3 VARCHAR(5000))
INSERT INTO #STATEMENT EXEC(@strSQL)
SELECT @STATMT=C3 FROM #STATEMENT
INSERT INTO LOGR(USERID,STRSQL,DATE,TIME,TABLNM) VALUES(@CLIENT,@STATMT,@DATE,@TIME,'PATIENT')