3

動的に構築され、変数に保存される非常に複雑なクエリがあります。

2番目の部分として、別の通常のクエリがあり、これらの両方の間に内部結合を作成したいと思います。

ここでもう少し簡単にするために、私の問題を説明するための小さな例を示します。
この小さな例では、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 
    ( ..... '

このようにして、元の文字列を作成していたように、パラメータの実際の値を関数/プロシージャ呼び出しに作成し、「従業員」ファイルを文字列に表すために必要なテーブル名を使用して、それを実行します。SQL は、行おうとしていた方法で @query インラインを動的に解釈していません。

于 2010-03-17T11:18:44.957 に答える