我有一个非常复杂的查询,它将通过动态构建并保存在一个变量中。
作为第二部分,我有另一个普通查询,我想在这两者之间进行内部连接。
为了使它更容易这里是一个小例子来说明我的问题。
对于这个小例子,我使用了AdventureWorks 数据库。
一些查询是动态建立的
(是的,我知道这里没有动态,因为这只是一个例子。)
DECLARE @query AS varchar(max) ;
set @query = '
select
HumanResources.Employee.EmployeeID
,HumanResources.Employee.LoginID
,HumanResources.Employee.Title
,HumanResources.EmployeeAddress.AddressID
from
HumanResources.Employee
inner join HumanResources.EmployeeAddress
on HumanResources.Employee.EmployeeID = HumanResources.EmployeeAddress.EmployeeID
;';
EXEC (@query);
我的正常查询
select
Person.Address.AddressID
,Person.Address.City
from
Person.Address
也许我想拥有但不起作用
select
@query.*
,Addresses.City
from
@query as Employees
inner join
(
select
Person.Address.AddressID
,Person.Address.City
from
Person.Address
) as Addresses
on Employees.AddressID = Addresses.AddressID