When should I use cross apply over inner join?

前端 未结 14 1067
忘了有多久
忘了有多久 2020-11-22 06:51

What is the main purpose of using CROSS APPLY?

I have read (vaguely, through posts on the Internet) that cross apply can be more efficient when selectin

14条回答
  •  一向
    一向 (楼主)
    2020-11-22 07:16

    Here is an article that explains it all, with their performance difference and usage over JOINS.

    SQL Server CROSS APPLY and OUTER APPLY over JOINS

    As suggested in this article, there is no performance difference between them for normal join operations (INNER AND CROSS).

    The usage difference arrives when you have to do a query like this:

    CREATE FUNCTION dbo.fn_GetAllEmployeeOfADepartment(@DeptID AS INT)  
    RETURNS TABLE 
    AS 
    RETURN 
       ( 
       SELECT * FROM Employee E 
       WHERE E.DepartmentID = @DeptID 
       ) 
    GO 
    SELECT * FROM Department D 
    CROSS APPLY dbo.fn_GetAllEmployeeOfADepartment(D.DepartmentID)
    

    That is, when you have to relate with function. This cannot be done using INNER JOIN, which would give you the error "The multi-part identifier "D.DepartmentID" could not be bound." Here the value is passed to the function as each row is read. Sounds cool to me. :)

提交回复
热议问题