一 .Server Trigger的簡單介紹 在SQL Server資料庫中,Server Trigger 是一種特殊類型的存儲過程,它可以對特定表、視圖或存儲中的必然事件自動響應,不由用戶調用。創建觸發器時對其進行定義,以便在對特定的資料庫對象作特定類型的修改時執行,根據觸發器定義的動作做出反應。 ...
一 .Server Trigger的簡單介紹
在SQL Server資料庫中,Server Trigger 是一種特殊類型的存儲過程,它可以對特定表、視圖或存儲中的必然事件自動響應,不由用戶調用。創建觸發器時對其進行定義,以便在對特定的資料庫對象作特定類型的修改時執行,根據觸發器定義的動作做出反應。
其主要被用在保持資料庫對象的完整性方面。例如,防止資料庫中已建好的表和存儲過程被更改或刪除。此外還可以 進行更改歷史記錄的追蹤,查看表或存儲被修改的記錄。
Server Trigger比Database Trigger所管控的範圍更廣,可以管控Server下的所有Database的對象。
二. 主要表 及創建腳本
表Protected_Objects ,主要用來存儲被保護的資料庫對象,例如 表和存儲過程。 欄位 ActiveFlag設置為Y時有效,N是無效。
有新的資料庫對象創建,最自動Insert一筆數據。
CREATE TABLE [dbo].[Protected_Objects]( [ServerIP] [varchar](100) NULL, [ServerName] [varchar](100) NULL, [DBName] [varchar](100) NULL, [ObjName] [varchar](100) NULL, [Objtype] [varchar](100) NULL, [Creator] [varchar](100) NULL, [ActiveFlag] [varchar](10) NULL, [TransDateTime] [datetime] NULL ) ON [PRIMARY] GO
表DBTrigger_Log,主要存儲資料庫對象變動記錄。
CREATE TABLE [dbo].[DBTrigger_Log]( [ServerIP] [varchar](20) NULL, [ServerName] [varchar](50) NULL, [DBName] [varchar](100) NULL, [ObjectName] [varchar](100) NULL, [ObjectType] [varchar](100) NULL, [EventType] [varchar](100) NULL, [HostName] [varchar](128) NULL, [AppName] [varchar](128) NULL, [EventData] [xml] NULL, [TransDateTime] [datetime] NULL, [Flag] [int] NULL DEFAULT ((0)) ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO SET ANSI_PADDING OFF GO EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'伺服器IP' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'DBTrigger_Log', @level2type=N'COLUMN',@level2name=N'ServerIP' GO EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'伺服器名稱' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'DBTrigger_Log', @level2type=N'COLUMN',@level2name=N'ServerName' GO EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'資料庫名稱' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'DBTrigger_Log', @level2type=N'COLUMN',@level2name=N'DBName' GO EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'對象名稱' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'DBTrigger_Log', @level2type=N'COLUMN',@level2name=N'ObjectName' GO EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'對象類型' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'DBTrigger_Log', @level2type=N'COLUMN',@level2name=N'ObjectType' GO EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'事件類型' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'DBTrigger_Log', @level2type=N'COLUMN',@level2name=N'EventType' GO EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'終端機器名' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'DBTrigger_Log', @level2type=N'COLUMN',@level2name=N'HostName' GO EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'名稱' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'DBTrigger_Log', @level2type=N'COLUMN',@level2name=N'AppName' GO EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'觸發事件xml' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'DBTrigger_Log', @level2type=N'COLUMN',@level2name=N'EventData' GO EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'發生時間' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'DBTrigger_Log', @level2type=N'COLUMN',@level2name=N'TransDateTime' GO EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'是否上傳' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'DBTrigger_Log', @level2type=N'COLUMN',@level2name=N'Flag' GO
三. 創建Server Trigger的腳本
USE [master] GO /****** Object: DdlTrigger [ServerDBTrigger_ProtectObjects] Script Date: 2018/12/27 13:36:00 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO /*########################################################################################### *Program*: <DB Trigger> *Description*: <Protect SQL key objects> *programer*: <> *Date*: 2015-12-03 ---0001 2015-12-03 11:12 第一階段期間只保留修改記錄,暫時不阻止(不RollBack) ---0002 2015-12-03 15:32 增加發郵件的功能. ---0003 2015-12-04 14:20 出現set ANSI_PADDING Off後,還有(如果是script出來的表,其中有索引約束等, --- 需要Alter表時,就會報錯。)代碼時,@xEvent.query會報錯。 ##############################################################################################*/ CREATE TRIGGER [ServerDBTrigger_DBA_ProtectObjects] ON ALL SERVER FOR DROP_TABLE,DROP_PROCEDURE,DROP_VIEW,DROP_FUNCTION, CREATE_TABLE,CREATE_PROCEDURE,CREATE_VIEW,CREATE_FUNCTION, ALTER_PROCEDURE,ALTER_VIEW,ALTER_TABLE,ALTER_FUNCTION,RENAME AS SET NOCOUNT ON ; BEGIN TRY DECLARE @ServerIP varchar(20) DECLARE @ServerName varchar(50) DECLARE @AppName nvarchar(128) DECLARE @HostName nvarchar(128) DECLARE @DBName varchar(100) DECLARE @ObjectName varchar(100) DECLARE @ObjectType varchar(100) DECLARE @EventType varchar(100) DECLARE @ObjectAction varchar(100) DECLARE @xEvent XML SET @xEvent = EVENTDATA() ----------------------0003 start ---------- --Set @DBName=CONVERT(VARCHAR(100),@xEvent.query('data(/EVENT_INSTANCE/DatabaseName)')) --Set @ObjectName=CONVERT(VARCHAR(100),@xEvent.query('data(/EVENT_INSTANCE/ObjectName)')) --Set @ObjectType=CONVERT(VARCHAR(100),@xEvent.query('data(/EVENT_INSTANCE/ObjectType)')) --Set @ObjectAction=CONVERT(VARCHAR(100),@xEvent.query('data(/EVENT_INSTANCE/EventType)')) DECLARE @EventData varchar(MAX) SELECT @EventData=CONVERT(VARCHAR(MAX),@xEvent) SET @DBName= SUBSTRING (@EventData, CHARINDEX('<DatabaseName>',@EventData)+14, CHARINDEX('</DatabaseName>',@EventData)-CHARINDEX('<DatabaseName>',@EventData)-14) SET @ObjectName= SUBSTRING (@EventData, CHARINDEX('<ObjectName>',@EventData)+12, CHARINDEX('</ObjectName>',@EventData)-CHARINDEX('<ObjectName>',@EventData)-12) SET @ObjectType= SUBSTRING (@EventData, CHARINDEX('<ObjectType>',@EventData)+12, CHARINDEX('</ObjectType>',@EventData)-CHARINDEX('<ObjectType>',@EventData)-12) SET @ObjectAction= SUBSTRING (@EventData, CHARINDEX('<EventType>',@EventData)+11, CHARINDEX('</EventType>',@EventData)-CHARINDEX('<EventType>',@EventData)-11) SET @EventType=SUBSTRING(@EventData, CHARINDEX('<EventType>',@EventData)+11, CHARINDEX('</EventType>',@EventData)-CHARINDEX('<EventType>',@EventData)-11) ------------0003 end --------------- SELECT @HostName=HOST_NAME(),@AppName=APP_NAME() SELECT @ServerName = @@SERVERNAME SELECT @ServerIP = MIN(LOCAL_NET_ADDRESS) FROM SYS.DM_EXEC_CONNECTIONS WHERE LOCAL_NET_ADDRESS IS NOT NULL IF EXISTS(SELECT TOP 1 ObjName FROM Protected_Objects WITH(NOLOCK) WHERE ServerName = @@SERVERNAME AND DBName=@DBName AND ObjName=@ObjectName AND ActiveFlag='Y') BEGIN IF (@ObjectName LIKE 'TMP%')OR (/*@ObjectAction LIKE 'ALTER%' AND */@ObjectName LIKE '[_]%') BEGIN INSERT INTO DBTrigger_Log ( ServerIP ,ServerName ,DBName ,ObjectName ,ObjectType,EventType ,HostName , AppName ,[EventData] ,TransDateTime) VALUES ( @ServerIP ,@ServerName , @DBName , @ObjectName ,@ObjectType ,@EventType,@HostName ,@AppName ,@EventData , GETDATE()) END ELSE BEGIN -----------------0001 start --- INSERT INTO DBTrigger_Log ( ServerIP ,ServerName ,DBName ,ObjectName ,ObjectType,EventType ,HostName , AppName ,[EventData] ,TransDateTime) VALUES ( @ServerIP ,@ServerName , @DBName , @ObjectName ,@ObjectType ,@EventType,@HostName ,@AppName ,@EventData , GETDATE()) --Rollback TRANSACTION -----------------end -------- -------------0002 begin ---------------- DECLARE @Subject AS nvarchar(200) DECLARE @Body AS nvarchar(MAX) DECLARE @SPName AS nvarchar(MAX) SET @Subject = 'ServerDBTrigger-重要!;ServerIP:' + @ServerIP SET @SPName = '' SET @Body = '<html><body>Dear All,<br> <br> ServerName:' + @ServerName+ ' ; ServerIP:' + @ServerIP+ '上的object已被改動,請及時檢查!!! <br> You can get detail information from DBA_DBTrigger_Log. <br><br><table border=1 bgcolor=#aaff11>' SET @Body = @Body+ '<tr bgcolor=#ffaa11><td>ServerName</td><td>ServerIP</td><td>DBName</td><td>EventType</td><td>ObjectName</td><td>ObjectType</td><td>HostName </td><td>TransDateTime</td></tr>' SELECT @SPName = @SPName + '<tr bgcolor=#ffaa11><td>'+ CAST(@ServerName AS NVARCHAR(50))+ '</td><td>'+ CAST(@ServerIP AS NVARCHAR(50))+ '</td><td>' + CAST(@DBName AS NVARCHAR(50)) + '</td><td>'+ CAST(@EventType AS NVARCHAR(50))+ '</td><td>'+CAST(@ObjectName AS NVARCHAR(50))+ '</td><td>'+ CAST(@ObjectType AS NVARCHAR(20))+ '</td><td>'+ SUBSTRING(REPLACE(CAST(@HostName AS varchar(500)), CHAR(0), ''), 1, 500)+ '</td><td>'+ CONVERT(varchar(100), GETDATE(), 21)+ '</td></tr>' SET @Body = @Body + @SPName + '</table>' SET @BODY=REPLACE(@BODY,'''','') IF REPLACE(@BODY,' ','')<>'' BEGIN DECLARE @AllEmailToAddress varchar(3000)='' DECLARE @AllEmailCcAddress varchar(3000)='' DECLARE @Allprofile_name varchar(100)='' SELECT @AllEmailToAddress='收件人的地址' SELECT @AllEmailCcAddress='抄送人的地址' SELECT TOP 1 @Allprofile_name=NAME FROM msdb.dbo.sysmail_profile ORDER BY profile_id EXEC msdb..sp_send_dbmail @profile_name = @Allprofile_name -- profile 名稱 ,@recipients = @AllEmailToAddress -- 收件人郵箱 ,@copy_recipients=@AllEmailCcAddress ,@subject = @Subject -- 郵件標題 ,@body = @BODY -- 郵件內容 ,@body_format = 'HTML' -- 郵件格式 ,@file_attachments='' END ------------- 0002 end ------------ END END ----新建對象自動塞入保護表 ELSE BEGIN --PRINT 3 DELETE FROM Protected_Objects WHERE ServerName = @@SERVERNAME AND DBName=@DBName AND ObjName=@ObjectName IF @ObjectAction LIKE 'Create%' AND @AppName LIKE '%Microsoft SQL Server Management Studio%' AND @ObjectName NOT LIKE '[_]%' AND @ObjectName NOT LIKE 'TMP%' BEGIN INSERT INTO Protected_Objects VALUES ( @ServerIP, @ServerName, @DBName, @ObjectName,@ObjectType, @HostName, 'Y', GETDATE() ) INSERT INTO DBTrigger_Log ( ServerIP ,ServerName ,DBName ,ObjectName ,ObjectType,EventType ,HostName , AppName ,[EventData] ,TransDateTime) VALUES ( @ServerIP ,@ServerName , @DBName , @ObjectName ,@ObjectType ,@EventType,@HostName ,@AppName ,@EventData , GETDATE()) END ELSE IF @ObjectAction NOT LIKE 'Create%' AND @AppName LIKE '%Microsoft SQL Server Management Studio%' AND @ObjectName NOT LIKE '[_]%' BEGIN INSERT INTO DBTrigger_Log ( ServerIP ,ServerName ,DBName ,ObjectName ,ObjectType,EventType ,HostName , AppName ,[EventData] ,TransDateTime) VALUES ( @ServerIP ,@ServerName , @DBName , @ObjectName ,@ObjectType ,@EventType,@HostName ,@AppName ,@EventData , GETDATE()) END END END TRY BEGIN CATCH PRINT '@ObjectName:'+@ObjectName PRINT '@ObjectType:'+@ObjectType PRINT ERROR_MESSAGE()