Friday, August 16, 2013

Triggers in SQL Can be used for Audit-Trial and many more.

Sql server triggers are better option for audit trial required for data change analysis for application development as well as Data base administration purpose.
Below are syntax for Update, Delete or insert trigger which will monitor changes in row label and insert data to another table having purpose of storing of changes .


Syntax:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
CREATE TRIGGER <Schema_Name, sysname, Schema_Name>.<Trigger_Name, sysname, Trigger_Name>
   ON  <Schema_Name, sysname, Schema_Name>.<Table_Name, sysname, Table_Name>
   AFTER <Data_Modification_Statements, , INSERT,DELETE,UPDATE>
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

    -- Insert statements for trigger here

END
GO

========================================================================
Example:

GO
/****** Object:  Trigger [dbo].[TrJournalUpdate]    Script Date: 03/08/2013 11:10:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create TRIGGER [dbo].[TrJournalUpdate] ON [dbo].[tbl_JournalMaster]
FOR UPDATE
AS
BEGIN
INSERT INTO tbl_JournalMaster_audittrial(JournalVoucherID,JVNo,JVDate,
Posted,ModuleName,Remarks,
SubmittedByID,SubmittedDate
)
SELECT JournalVoucherID,JVNo,JVDate,
Posted,ModuleName,Remarks,
SubmittedByID,SubmittedDate
FROM Deleted
END