In one of my project requirement was to find out the (Day-Hours-Minutes) difference between two datetime fields. So I wrote a function in SQL server to find out that difference in Day-Hours-Minutes format.
Below is the Code.....
CREATE [dbo].[FindDateDiff]
(
@StartDate DATETIME,
@EndDate DATETIME
)
RETURNS VARCHAR(100)
AS
BEGIN
DECLARE
@dateDay INT,
@dateHour INT,
@dateMin INT
SET @dateMin =CASE WHEN @EndDate IS NULL THEN DATEDIFF(mi,@StartDate,GETDATE()) ELSE DATEDIFF(mi,@StartDate,@EndDate) END
IF(@dateMin > =60)
BEGIN
SELECT @dateHour=@dateMin / 60;
SELECT @dateMin=@dateMin % 60;
IF(@dateHour >=24 )
BEGIN
SELECT @dateDay=@dateHour / 24;
SELECT @dateHour=@dateHour % 24;
END
ELSE
BEGIN
SET @dateDay =0;
END
RETURN CONVERT(VARCHAR(100),@dateDay)+'-'+CONVERT(VARCHAR(100),@dateHour)+'-'+CONVERT(VARCHAR(100),@dateMin) ;
END
ELSE
BEGIN
RETURN '0-0-'+CONVERT(VARCHAR(100),@dateMin) ;
END
RETURN '0-0-0';
END
--select [dbo].[FindDateDiff] ('06/05/2008 6:28:00 PM','11/06/2008 7:28:00 PM')
No comments:
Post a Comment