Tuesday, August 14, 2012

Trigger in sql server 2008 with example

CREATE TRIGGER [dbo].[Tri_TriggerName_History]
    ON [dbo].[Tbl_TableName]
    FOR INSERT, UPDATE, DELETE
AS
    IF (SELECT COUNT(*) FROM inserted) > 0
    BEGIN
        IF (SELECT COUNT(*) FROM deleted) > 0
        BEGIN
                        INSERT INTO [dbo].[ Tbl_TableName _HistryTable]
                        (                      
                        PlanID ,
                        SSNId,
                        CreatedBy    ,
                        CreatedDate,
                        UpdatedBy,
                        UpdatedDate,
                        Operation
                        )
    select PlanID,
                        SSNId,                        
                        CreatedBy  ,
                        CreatedDate,
                            'USER',
                            GETDATE(),
                            'DATA UPDATED' FROM DELETED
        END
        ELSE
        BEGIN
    INSERT INTO [dbo].[ Tbl_TableName _HistryTable ]
                        (
                                               
                                                PlanID,
                                                SSNId,                                               
                                                CreatedBy    ,
                                                CreatedDate,
                                                UpdatedBy,
                                                UpdatedDate,
                                                Operation
                        )
    select            PlanID   ,
                        SSNId,                      
                        CreatedBy     ,
                        CreatedDate,
                            'USER',
                            GETDATE(),
                            'DATA INSERTED' FROM INSERTED
        END
    END
  
GO



No comments: