Sunday, February 21, 2016

Trigger to find insert update and delete on table

 use db name 
go 

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER  TRIGGER [dbo].[tr_TableAudit_AccountTbl] 
   ON [dbo].Account
   AFTER INSERT, DELETE, UPDATE
AS 
BEGIN
SET NOCOUNT ON;


BEGIN TRY
IF EXISTS (SELECT * FROM DELETED) OR EXISTS (SELECT * FROM INSERTED)
BEGIN
DECLARE @Database_Name sysname, @Schema_Name sysname, @Trigger_Name sysname;
SELECT @Database_Name = DB_NAME(), @Schema_Name = OBJECT_SCHEMA_NAME([parent_id]), @Trigger_Name = OBJECT_NAME([parent_id])
FROM sys.triggers WHERE object_id = @@PROCID;

----get the result set
WITH XML_Values AS (
SELECT 
@Database_Name + '.' + @Schema_Name + '.' + @Trigger_Name AS [TableName],
(SELECT * FROM DELETED D1 WHERE D1.AccountID=D.AccountID FOR XML RAW, ROOT, TYPE, ELEMENTS XSINIL) AS [OldRecord],
(SELECT * FROM INSERTED I1 WHERE I1.AccountID=I.AccountID FOR XML RAW, ROOT, TYPE, ELEMENTS XSINIL) AS [NewRecord],
COALESCE(I.AccountID, D.AccountID) As RecordID--Added new 
FROM Inserted I
FULL OUTER JOIN Deleted D ON I.AccountID=D.AccountID
)


INSERT INTO [AuditLog] 
( [TableName], 
[OldRecord], 
[NewRecord],
[RecordID]--Added New
)

SELECT 
[TableName],
[OldRecord],
[NewRecord],
   [RecordID]
 
FROM XML_Values
WHERE ISNULL(CONVERT(VARCHAR(MAX), [OldRecord]), '')<>ISNULL(CONVERT(VARCHAR(MAX), [NewRecord]), '');
END
END TRY
BEGIN CATCH
-- No op
END CATCH
END





No comments:

Post a Comment

https://blog.sqlauthority.com/2009/06/27/sql-server-fix-error-17892-logon-failed-for-login-due-to-trigger-execution-changed-database-context...