Sunday, 26 March 2017

Delete records \ data from large SQL tables

/**********************************************/
Delete Script - To delete records from large History tables
/**********************************************/

It is many times required to delete records from History tables which stay in database unattended.
When you try to delete specific set of records or even one record, the Management console hangs. Here is how you can delete required records easily.

Table : masDispatchHistory
Identity Column : iDispatchHistory
/**********************************************/


--Select Count(1) from masDispatchHistory

Declare  @i bigint, @max bigint
Select @i=min(iDispatchHistory),@max = max(iDispatchHistory) from masDispatchHistory
Print @i
Print @max
--set @i = 4760077 -- Set this value here in case you want to start from a known value and avoid extra loops
While (@i < @max)
Begin
    Print @i
    delete from [dbo].masDispatchHistory where iDispatchHistory < @i
    set @i = @i+1000
    Waitfor delay '00:00:01:000' -- Wait so that SQL gives time for other internal processes to run and execute. This will not hang your system
End


-- Do comment if you need any help.

Saturday, 25 March 2017

Best Way to Create Audit trail logs for SQL tables

How to create Audit trail or Trail Logs for SQL tables


Hi guys, its a common requirement for having audit trails for data changes in SQL table. This article will help you create audit trails for MS SQL.

Audit trail is having a records of WHO has changed WHICH value with WHAT value in a database table value WHEN.

1) Create the TrailLog Table

CREATE TABLE [dbo].[masAuditTrailLog](
    [iAuditTrailLog] [bigint] IDENTITY(1,1) NOT NULL,
    [TableName] [varchar](50) NULL,
    [PKName] [varchar](50) NULL,
    [PKValue] [bigint] NULL,
    [ColumnName] [varchar](100) NULL,
    [OldValue] [varchar](500) NULL,
    [NewValue] [varchar](500) NULL,
    [ChangedBy] [int] NOT NULL,
    [ChangeDate] [datetime] NOT NULL CONSTRAINT [DF_masAuditTrailLog_ChangeDate]  DEFAULT (getdate())
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO


2) Simply add following code in your Update procedure and relax.
 Your Update statement should be in         "--Here goes your Update Statement" place
You can make the SQL dynamic in case you need to make multiple logs


/***************************************************************************************************/
        /* Audit Trail section */
        /***************************************************************************************************/
        /* Get old values in #Updated table */
        Declare @ID bigint, @ChangedByUser int
        Declare @TableName Varchar(50), @PKName Varchar(50)

        SET @ChangedByUser = @iUser -- Set your UserID here
        SET @ID = @SiteID --Set ID value to @parameter for Update
        Set @TableName='mLocationDetails' -- Set your table name here
        Set @PKName='SiteID' -- Set your PK name here

--Get the record to be tracked
        Select * into #Updated from mLocationDetails where SiteID = @ID

        /*=================   Update The records =================*/
        --Here goes your Update Statement
        -- eg. Update Table set col = val, col=val where ID=@ID
        /*=================   Update The records =================*/

        /* Set all column names in below queries for which you want Audit Trail */
        Select * into #tmp from (
        Select 'OldValue' as
-- Your Updated columns names in below line
ColumnName,Convert(varchar(50),iSiteEvaluator)'iSiteEvaluator',Convert(varchar(50)
from #Updated
        Union
        Select 'NewValue' as
-- Your Updated columns names in below line 
ColumnName,Convert(varchar(50),iSiteEvaluator)'iSiteEvaluator',Convert(varchar(50)
from mLocationDetails
         where SITEID = @ID
        ) as tmp

        Select * into #PIVOT from
        (Select * from
        (Select ColumnName, COLName, value from #tmp
          unpivot
          (
            value for COLName in
-- Your Updated columns names in below line (iSiteEvaluator,EvaluatorExpRent,FSGExpRent,FinalRent,FSGiOutageHrs,FSGiOutageType,SiteEvaluatorRemarks)
          ) unpiv
        ) src
        pivot
        (
          MAX(value)
          for ColumnName in ([OldValue], [NewValue])
        ) piv) as ABC

        Delete from #PIVOT where OldValue = NewValue
        Delete from #PIVOT where OldValue is NULL and NewValue =''
        Delete from #PIVOT where OldValue = '' and NewValue is NULL
        /* Insert in masAuditTrailLog table */
        Insert into masAuditTrailLog Select @TableName,@PKName,@ID,COLName,OldValue,NewValue,@ChangedByUser,Getdate() from #PIVOT

        /* drop all temp tables */
        Drop table #Updated
        Drop table #tmp
        Drop table #PIVOT
        /***************************************************************************************************/
        /***************************************************************************************************/

Do comment if you need any help.