必须声明表变量“@myTable”

时间:2016-06-01 10:49:16

标签: sql-server tsql

DECLARE @myTable TABLE( 
Name VARCHAR(50), 
Year INT, 
Hours INT ) 

INSERT INTO @myTable *.... some values*

DECLARE @var INT 
SET @var = 2015

DECLARE @DynamicPivot VARCHAR(MAX) 

SET @DynamicPivot = 'SELECT * FROM
@myTable  PIVOT( SUM(Hours) FOR Year IN (' + @var + ') ) AS PvtTable

EXEC sp_executesql @DynamicPivot

我正在尝试创建动态表并使用pivot旋转表。 @var中的值是动态表Year INT中已存在的值。一切正常,除非我尝试执行动态数据透视。它给出了@myTable未声明的错误,即使我同时运行整个代码。这个问题很可能在我所说的枢轴声明中并没有真正找到问题。有什么想法吗?

3 个答案:

答案 0 :(得分:5)

使用 () => (list, list).forEach((i,j) => connect(i,j)) 临时表和#仅适用于sp_executesql

nvarchar

答案 1 :(得分:4)

您应该在动态查询中使用表变量..

DECLARE @DynamicPivot VARCHAR(MAX) 

SET @DynamicPivot = '
DECLARE @myTable TABLE( 
Name VARCHAR(50), 
Year INT, 
Hours INT ) 

INSERT INTO @myTable *.... some values*

DECLARE @var INT 
SET @var = 2015

SELECT * FROM
@myTable  PIVOT( SUM(Hours) FOR Year IN (' + @var + ') ) AS PvtTable'

EXEC sp_executesql @DynamicPivot

答案 2 :(得分:3)

试试这个,必须在动态查询中声明变量。

DECLARE @DynamicPivot VARCHAR(MAX) 

DECLARE @var INT 
SET @var = 2015

SET @DynamicPivot = '
DECLARE @myTable TABLE( 
Name VARCHAR(50), 
Year INT, 
Hours INT ) 

INSERT INTO @myTable *.... some values*

SELECT * FROM
@myTable  PIVOT( SUM(Hours) FOR Year IN (' + @var + ') ) AS PvtTable'

EXEC sp_executesql @DynamicPivot