2016-05-16 52 views
0

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

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 
+2

有几种方法可以做到这一点。您可以使用cte,派生表或者很可能只需加入表格。但是,实现这一点的巨大荣誉并不是非常有效。 –

回答

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 
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操作中使用的子查询返回一个记录。

+0

如果'where id = 1'为False或Unknown并且'其中p1 = @ p1'为True,那么原始查询将返回至少一行,但此解决方案...不是。 –

+0

2行CROSS JOIN 0行= 0行 –

1

我认为变量是最接近LINQ 条款。例如:

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; 

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