介紹
APPLY 主要用於將某一個子查詢和一個 資料表函式 (Table Function) 做 JOIN 運算,有別於 JOIN 運算,APPLY 不使用 ON 選擇關聯欄位,則是將欄位帶入方式使用。子查詢結果會被當作為 left ,而 資料表函式 當作 right 進行運算。
CROSS APPLY 和 OUTER APPLY 是從 SQL Server 2005 新增的語法,其使用時資料庫相容層級要90。這兩個語法效果等同於 INNER JOIN 與 LEFT OUTER JOIN。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SELECT A.column1, ... ,B.column1, ... | |
FROM TableA AS A | |
CROSS APPLY TableFunction (A.Id) AS TF |
這邊舉一個例子來看看 (範例有一點差,但我們直接看效果)
Employee 資料表內容如下
Dept 資料表內容如下:
首先我們先建立資料表函式
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE FUNCTION GetDept(@CountryName varchar(25)) | |
RETURNS TABLE | |
RETURN | |
( | |
SELECT Id, Name, CountryName | |
FROM Dept | |
WHERE CountryName = @CountryName | |
) |
我們使用 CROSS APPLY 語法並看其結果
接下來我們使用 OUTER APPLY
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SELECT E.Id, E.Name, E.CountryName, TD.Name, E.CountryName | |
FROM EMPLOYEE AS E | |
OUTER APPLY GetDept(E.CountryName) TD |
參考資料
使用 APPLY - https://technet.microsoft.com/zh-tw/library/ms175156(v=sql.105).aspx
0 留言