2

I have a need for a single select statement that runs another select statement within its from clause and the result (there's only one record) is the table name of the outer select.

For this purpose, I cannot use a stored procedure, exec, or @ variables.

Also, the query file must start with 'select' and contain only that statement.

I know there are better ways to accomplish the end result, however the vendor's wizard that the query must run through sniffs for anything other than a single select statement. Its frustrating, but that's all we have to work with.

Here is an example of what I am trying to do:

select
  plan.TransactionID,
  plan.PlanName,
  sum(plan.Value) as Rate 
from
  (select 'dbo._Result' + ltrim(str(CalculationID)) from dbo.Calculation where Name = 
    'TPRL Transaction Plan Rates'
  ) Plan

Of course, this does not work. However, neither does this:

select
  plan.TransactionID,
  plan.PlanName,
  sum(plan.Value) as Rate 
from
  exec(select 'dbo._Result' + ltrim(str(CalculationID)) from dbo.Calculation where Name = 'TPRL Transaction Plan Rates') Plan

Even though, this by itself does pull back the table I want into a result set:

exec(select 'dbo._Table' + ltrim(str(CalculationID)) from dbo.Calculation where Name = 'TPRL Transaction Plan Rates')

All I would need for it to do is treat the result as a literal (as in, macro substitution) in the from above, but it doesn't work that way.

Is there a way in tsql to do this?

4

2 に答える 2

1

いいえ、これは非動的TSQLだけでは実行できません。TSQLでは、テーブル名を変数にすることもパラメータ化することもできません。これは、動的TSQLでのみ実行できます。

EXEC('sql command')また、動的TSQLは、またはのいずれかでのみ実行できますsp_ExecuteSql(..)

これを回避するための可能な方法: 使用している機能に独自のマクロ置換がない限り、次のいずれか

  1. クライアントに最初に内部SQLクエリを実行させてテーブル名を決定し、次にそれに基づいて新しいファイル/文字列を作成します。また
  2. ある種のハッカーSQLインジェクションのトリックを使用して、上記の動的SQLコマンドの1つを実行しているときに、SELECTを実行していると思わせるように施設​​を騙します。
于 2012-12-13T19:37:13.283 に答える
1

最初のクエリは機能するはずです。FROMステートメントでサブクエリを実行できます。どのようなエラーが発生していますか?

その必要性を理解した後、動的SQLが必要になると思います。

于 2012-12-13T19:24:35.560 に答える