针对相同 table 结果的外部应用(和交叉应用)

Outer apply (and cross apply ) against the same table result

考虑以下脚本(使用 SQL Server 2017):

declare @mytable as table (n int identity(1,1), name varchar(10),mydate  date)
insert into @mytable(name,mydate) values('a','01/01/2019')

select * from @mytable t1
cross apply (select   * from t1 ) t2;

select *,mydate from @mytable t1
cross apply (select   * from t1 ) t2

你怎么解释

  1. 我得到 5 行

  2. 第 1 列和第 2 列被命名为 c1 和 c2 而不是 @mytable

  3. 中的原始名称
  4. 我没有在脚本一中得到我的日期,只有我写了它才能得到它(* 是不够的)

  5. "this is a text" 在第 2 行到第 5 行返回 => 你如何解释?

您的 CROSS APPLY 定义是 select * from t1 - 这不是来自上面定义的别名的 select。相反,它会从中查找名为 t1 和 select 的 table - 这与查询的其余部分毫无关联。

如果你想APPLY别名table当前行的值,你需要

select * from @mytable t1
cross apply (select   t1.*  ) t2;

没有 FROM.

这符合您的预期。