SQL 中 CROSS APPLY 與 OUTER APPLY 的實際應用情境
SQL 中的 OUTER APPLY 和 CROSS APPLY 運算子提供了靈活的資料操作和複雜查詢執行方式。以下是一些實際用例,示範了何時使用每個運算符:
CROSS APPLY
<code class="language-sql">SELECT pr.name, pa.name FROM sys.procedures pr OUTER APPLY (SELECT TOP 2 * FROM sys.parameters pa WHERE pa.object_id = pr.object_id ORDER BY pr.name) pa ORDER BY pr.name, pa.name </code>
<code class="language-sql">SELECT * FROM sys.dm_exec_query_stats AS qs CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle)</code>
OUTER APPLY
<code class="language-sql">SELECT number, doubled_number, doubled_number_plus_one FROM master..spt_values CROSS APPLY (SELECT 2 * CAST(number AS BIGINT)) CA1(doubled_number) CROSS APPLY (SELECT doubled_number + 1) CA2(doubled_number_plus_one) </code>
<code class="language-sql">CREATE TABLE T ( Id INT PRIMARY KEY, Foo1 INT, Bar1 INT, Foo2 INT, Bar2 INT, Foo3 INT, Bar3 INT );</code>
使用 VALUES 語法 (SQL Server 2008 ):
<code class="language-sql">SELECT Id, Foo, Bar, GrpName FROM T CROSS APPLY (VALUES('1', Foo1, Bar1), ('2', Foo2, Bar2), ('3', Foo3, Bar3)) V(GrpName, Foo, Bar); </code>
以上是在 SQL 何時使用 CROSS APPLY 與 OUTER APPLY?的詳細內容。更多資訊請關注PHP中文網其他相關文章!