2016-08-08 15 views
3

私はsp_executesqlを@queryパス一時テーブルは、execするsp_executesqlを

set @query = 'SELECT GsName, ' + @cols + ' from 
     (
      select GSName, [THour], NumOfTransactions 
      from @table 
     ) x 
     pivot 
     (
      max([NumOfTransactions]) 
      for [THour] in (' + @cols + ') 
     ) p ' 
+0

可能な複製をhttp://stackoverflow.com/questions([\ _executesql SPにテーブル変数を渡す]を/ 4258798/pass-a-table-variable-to-sp-executedql) –

答えて

1

あなたがここにあることは​​ではありませんが、Table-Valued ParameterにEXECモードに一時テーブル(@table)を渡すことができますどのように。

テーブル値パラメータは、ユーザー定義テーブル タイプを使用して宣言されます。テンポラリテーブルまたは多くの パラメータを作成せずに、テーブル値パラメータを使用して データの複数の行をTransact-SQL文またはルーチン(例: プロシージャまたはファンクション)に送信できます。

sp_executesqlは、テーブル値のパラメータをサポートしますが、宣言された型である必要があります。

-- So, first we must declare User-Defined Table Type 
CREATE TYPE udtYB_Test AS TABLE(GSName nvarchar(100), THour time, NumOfTransactions int); 
GO 

-- Now we can create Table-Valued Parameter 
Declare @table udtYB_Test; 

-- And store there some data 
Insert Into @table (GSName, THour, NumOfTransactions) 
Values ('Sample', SYSUTCDATETIME(), 1); 

-- Just for the reference 
Select * From @table; 

-- To pass variable to sp_executesql we need parameters definition 
DECLARE @ParmDefinition nvarchar(500) = N'@table udtYB_Test READONLY'; 
-- Please note: table-valued parameter must be READONLY 

-- Here I use simplified query for demonstration only 
DECLARE @query nvarchar(500) = 'SELECT * FROM @table'; 

-- and the result should be identical to the reference above 
EXECUTE sp_executesql @query, @ParmDefinition, @table = @table; 

-- User-Defined Table Type cleanup 
DROP TYPE udtYB_Test; 
GO 

が最も実用的なケースでは、それは一時テーブルを使用する方がはるかに簡単です:の

Create Table #table (GSName nvarchar(100), THour time, NumOfTransactions int); 
Insert Into #table (GSName, THour, NumOfTransactions) Values ('Sample', SYSUTCDATETIME(), 1); 
Select * From #table; 
DECLARE @query nvarchar(500) = 'SELECT * FROM #table'; 
EXECUTE sp_executesql @query; 
Drop Table #table; 
関連する問題