• SQLRNNR (2/16/2014)


    dwain.c (2/16/2014)


    If you don't have a numbers table at your disposal like Jason does, this will also work.

    DECLARE @sometab TABLE (Person INT, [Date] DATE, [Hours] DECIMAL(12,2))

    INSERT INTO @sometab

    ( Person, Date, Hours )

    VALUES ( 101,'02/01/2014',1.00),(101,'02/02/2014',1.5);

    WITH Tally (n) AS

    (

    SELECT TOP ((SELECT 1+CAST(4*MAX([Hours]) AS INT) FROM @sometab))

    ROW_NUMBER() OVER (ORDER BY (SELECT NULL))

    FROM sys.all_columns

    )

    SELECT Person, [Date], [Hours]=DATEADD(minute, 15*n, CAST('00:00' AS TIME))

    FROM @sometab a

    CROSS APPLY

    (

    SELECT n

    FROM Tally

    WHERE n <= 4.*[Hours]

    ) b

    ORDER BY Person, [Date], n;

    Shhh... I was waiting for somebody to ask about that 😉

    Since the secret is out ;-), please see the following article for what a Tally Table or similar structure is an how it can be used to replace certain loops in a very high performance manner. It'll change the way you think in T-SQL.

    http://www.sqlservercentral.com/articles/T-SQL/62867/

    --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)