TSQL如何在子查询中重用记录

时间:2016-05-16 19:33:59

标签: sql-server linq tsql subquery

我有一个类似于以下的查询,我需要从另一个表中返回一些字段作为子查询。有没有办法我只能调用一次查询到TABLE2并使用该查询的结果来填充我需要的各个字段?我正在寻找类似于如何在LINQ中使用let语句的东西。谢谢。

select

(select field1 from TABLE2 where id = 1) as field1,
(select field2 from TABLE2 where id = 1) as field2,
(select field3 from TABLE2 where id = 1) as field3,
(select field4 from TABLE2 where id = 1) as field4 

from mainTable where p1 = @p1

3 个答案:

答案 0 :(得分:1)

我会使用OUTER APPLY:

select

x.field1 as field1,
x.field2 as field2,
x.field3 as field3,
x.field4 as field4 

from mainTable as mt
outer apply (select field1, field2, field3, field4 from TABLE2 where id = 1) as x
where p1 = @p1

答案 1 :(得分:1)

我认为变量最接近LINQ let 子句。例如:

declare @field1 bigint;
declare @field2 nvarchar(64);

select @field1 = field1, @field2=field2 from TABLE2 where id = 1;


select @field1, @field2, SomeOtherField from mainTable
where p1 = @p1;

当然,您需要设置适当类型的变量。

答案 2 :(得分:0)

您可以使用CROSS JOIN

select t.field1, t.field2, ...
from mainTable 
cross join (select field1, field2, ... from TABLE2 where id = 1) as t
where p1 = @p1

我假设cross join操作中使用的子查询只返回一条记录。