- Learn T-SQL Querying
- Pedro Lopes Pam Lahoud
- 279字
- 2021-06-24 14:38:10
APPLY
APPLY is like a cross join in the type of result set that it produces, but usable only with functions. In a cross join, both inputs (left and right) are tables or views that already exist in the database, with a fixed definition. However, APPLY is used in scenarios where a join cannot be used. In APPLY, one of the inputs (the right) is not physically materialized in the database because its output is dependent on input parameters, such as in the case of a table-valued function (TVF).
For example, the AdventureWorks sample database has a SalesPerson table that contains the BusinessEntityID and SalesYTD columns, and a ufnGetContactInformation TVF that returns the FirstName, LastName, and JobTitle columns. The TVF creates a runtime abstraction for columns that exist in multiple underlying tables, like building a table on-the-fly. To write a query that returns the year-to-date (YTD) sales per sales person, together with their name and job title, a cross apply can be used to return all rows from the SalesPerson table, and each of those rows is combined with the rows coming from the ufnGetContactInformation TVF.
The query would look like the following code block:
SELECT SP.SalesYTD, P.FirstName, P.LastName, P.JobTitle
FROM Sales.SalesPerson AS SP
CROSS APPLY dbo.ufnGetContactInformation (SP.BusinessEntityID) AS P;
In the following screenshot, the results of the ufnGetContactInformation function are displayed alongside the SalesYTD column, just as if they came from another table using a simple inner or outer join:

However, the following query produces an error (ID 4104) because a join cannot be used directly with a TVF:
SELECT SP.SalesYTD, P.FirstName, P.LastName, P.JobTitle
FROM Sales.SalesPerson AS SP
CROSS JOIN dbo.ufnGetContactInformation (SP.BusinessEntityID) AS P;
- 亮劍.NET:.NET深入體驗與實戰精要
- Microsoft Dynamics CRM Customization Essentials
- Verilog HDL數字系統設計入門與應用實例
- 教父母學會上網
- Effective DevOps with AWS
- Google App Inventor
- 空間傳感器網絡復雜區域智能監測技術
- Embedded Programming with Modern C++ Cookbook
- 可編程序控制器應用實訓(三菱機型)
- 基于ARM9的小型機器人制作
- 經典Java EE企業應用實戰
- AVR單片機工程師是怎樣煉成的
- 暗戰強人:黑客攻防入門全程圖解
- 暗戰強人:黑客及反黑客工具快速精通
- 我的IT世界