官术网_书友最值得收藏!

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;
主站蜘蛛池模板: 含山县| 宣恩县| 莱西市| 都兰县| 利辛县| 榆林市| 桐庐县| 梅州市| 土默特右旗| 澄城县| 库伦旗| 江油市| 托里县| 出国| 广德县| 全南县| 吉安市| 宁安市| 通州市| 金湖县| 桑植县| 威信县| 伊吾县| 台东市| 广汉市| 吴川市| 东明县| 翁牛特旗| 容城县| 太仆寺旗| 雅安市| 渑池县| 图们市| 新巴尔虎右旗| 兴化市| 松溪县| 兰坪| 古丈县| 伊春市| 雅安市| 凤山市|