3

我有一个非常复杂的查询,它将通过动态构建并保存在一个变量中。

作为第二部分,我有另一个普通查询,我想在这两者之间进行内部连接。

为了使它更容易这里是一个小例子来说明我的问题。
对于这个小例子,我使用了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
4

2 回答 2

2

使用临时表并将记录转储到其中(来自动态查询)并使用临时表加入您拥有的静态查询。

set @query = 'CREATE table #myTempTable AS
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
    Employees.*
    ,Addresses.City
from
    #myTempTable as Employees
    inner join
    (
        select
            Person.Address.AddressID
            ,Person.Address.City
        from
            Person.Address
    ) as Addresses
    on Employees.AddressID = Addresses.AddressID
于 2010-03-17T11:19:28.170 回答
1

您可能走在正确的轨道上,但只要您信任参数的来源并且不暴露于 SQL 注入,您可能只需要在构建 @query 时更改您的选择,例如:

parameter to your function  '@YourAlternateTableParm'

DECLARE @query AS varchar(max) ; 

set @query = 'select ' + @YourAlternateTableParm 
  + '.*, Addresses.City
from ' + @YourAlternateTableParm
  + ' as Employees 
    inner join 
    ( ..... '

这样,就像您构建原始字符串一样,您正在将参数的实际值构建到函数/过程调用中,并使用表名将您的“Employees”文件表示到字符串中,然后执行它。SQL 没有按照您尝试的方式动态解释 @query 内联。

于 2010-03-17T11:18:44.957 回答