- 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;
- 機器學習實戰(zhàn):基于Sophon平臺的機器學習理論與實踐
- Word 2003、Excel 2003、PowerPoint 2003上機指導與練習
- 火格局的時空變異及其在電網(wǎng)防火中的應用
- Seven NoSQL Databases in a Week
- Learning Social Media Analytics with R
- Windows程序設計與架構
- AutoCAD 2012中文版繪圖設計高手速成
- 大數(shù)據(jù)驅動的設備健康預測及維護決策優(yōu)化
- 網(wǎng)絡化分布式系統(tǒng)預測控制
- Visual Basic.NET程序設計
- 悟透JavaScript
- 運動控制系統(tǒng)
- Cloud Security Automation
- Visual Studio 2010 (C#) Windows數(shù)據(jù)庫項目開發(fā)
- 強化學習