• Luis Cazares - Monday, December 18, 2017 1:44 PM

    I would take some benefit of using the integers behind and performance improvement of using an inline table-valued function.

    CREATE FUNCTION dbo.ifn_DifferenceBetweenDates
    (
      @Date1 Datetime, -- Dia inicio
      @Date2 Datetime -- Dia fin
    -- Formato: #d HH:MM:SS
    -- Sample:
    -- Set dateformat ymd
    -- SELECT *
    -- FROM SomeTable st
    -- CROSS APPLY dbo.ifn_DifferenceBetweenDates( st.Date1, st.Date2) --Samples '2017-10-01 01:46:00', '2017-10-17 10:45:00'
    -- Return: 16d 08:59:00
    )
    RETURNS TABLE
    AS
    RETURN
    SELECT CONVERT( varchar(10), CONVERT(int, Date2 - Date1)) + 'd ' + CONVERT(char(8), Date2 - Date1, 108) AS DiferenciaenHoras
    FROM (SELECT CASE WHEN @Date1 <= @Date2 THEN @Date1 ELSE @Date2 END AS Date1,
         CASE WHEN @Date1 <= @Date2 THEN @Date2 ELSE @Date1 END AS Date2)x

    GO

    +1000.  It also avoids returning a short string as a MAX blob not to mention avoiding a scalar function.

    Ah... sorry.  Found the same error in it that Scott did.

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)