Thursday, December 22, 2011

Time difference between two columns in sql server

Suppose our requirement is to calculate working hours for Employee in particular company.
Below example is shows the how to create the table and update the Working hours for every employee.


USE tempdb
GO

/*****************************************
Copyright      :
Author           : Raju M
Date              : 12/22/2011
Module         :
Desc              : Script to Create EmpTime table.

Change History :
Name        Date        Description

SELECT * FROM EmpTime

******************************************/

IF NOT EXISTS(SELECT * FROM sys.objects WHERE TYPE= 'U' AND Name = 'EmpTime')
BEGIN
    /*    Creating the EmpTime Table    */
    CREATE TABLE EmpTime
    (
        EmployeeID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
        StartingTime DATETIME NOT NULL,
        FinishingTime DATETIME NOT NULL,
        DeductBreakMM BIGINT NOT NULL,
        WorkingTime TIME(3) NULL
    )

    /*    Inserting the Data into EmpTime Table    */
    INSERT INTO EmpTime
        (
            StartingTime,
            FinishingTime,
            DeductBreakMM
        )

    SELECT '2011-12-22 09:58:07.943' AS StartingTime,
           '2011-12-22 19:18:07.003' AS FinishingTime,
           45 DeductBreakMM

    UNION ALL

    SELECT '2011-12-22 08:28:07.943' AS StartingTime,
           '2011-12-22 21:18:07.003' AS FinishingTime,
           51 DeductBreakMM


    /*    Updating the EmpTime Column in EmpTime Table    */
    UPDATE EmpTime
    SET WorkingTime = CAST(DATEADD(SS,(DATEDIFF(SS,StartingTime, FinishingTime)) - (DeductBreakMM*60),0) AS TIME(3))

END
GO

No comments:

Post a Comment