• cs (8/14/2009)


    If someone could explain how cross apply works, I'd be a very happy man 🙂

    I'll give it a try.

    CREATE TABLE #SomeTable (Col1 int)

    Insert into #SomeTable Values (1)

    Insert into #SomeTable Values (2)

    Insert into #SomeTable Values (3)

    Insert into #SomeTable Values (4)

    GO

    CREATE Function dbo.SomeFunction (@Input int)

    RETURNS TABLE AS

    RETURN (SELECT @Input-1 AS Result union all SELECT @Input AS Result)

    GO

    SELECT Col1, func.result

    FROM #SomeTable st CROSS APPLY dbo.someFunction(st.Col1) AS func

    For each row in SomeTable the CROSS APPLY will run the table-valued function dbo.SomeTable and pass it the value of Col1 from that row of SomeTable. Based on the table and function created above, the results would be

    1,0

    1,1

    2,1

    2,2

    3,2

    3,3

    4,3

    4,4

    Make sense so far?

    Cross apply is like inner join, if the function doesn't return a row for a particular parameter, that parameter won't appear in the resultset. If you want outer join behaviour, use OUTER APPLY

    Cross apply with a subquery is pretty much the same as with a function, it's the subquery that's run once for each row. The equivalent of that function above with a subquery would be this:

    SELECT Col1, func.result

    FROM #SomeTable st CROSS APPLY

    (SELECT st.Col1 UNION ALL SELECT st.Col1-1 ) AS func

    Gail Shaw
    Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
    SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability

    We walk in the dark places no others will enter
    We stand on the bridge and no one may pass