从Exec子句插入数据

时间:2014-02-25 23:39:47

标签: sql sql-server

知道为什么我一直收到#temp2是无效对象的错误吗?

我正在尝试使用EXEC命令执行的动态查询填充此表:

set @sql = 'Select DFRId, FiscalDate, Franchise_Number, Store_Number, Reviewer, '+@listStr+' from (Select DFRId, Reviewer, FiscalDate, Franchise_Number, Store_Number, Question, Score from #temp) as sourcetable Pivot (Max(Score) for Question in ('+@listStr+')) as pivotable order by Franchise_Number,Store_Number,FiscalDate  '

Insert #temp2 exec(@Sql)

2 个答案:

答案 0 :(得分:1)

首先,确保创建了临时表#temp2。

接下来,检查以下代码。

我希望你的问题能够解决..

set @sql = 'INSERT INTO #temp2 
Select DFRId, FiscalDate, Franchise_Number, Store_Number, Reviewer, '+@listStr+' from (Select DFRId, Reviewer, FiscalDate, Franchise_Number, Store_Number, Question, Score from #temp) as sourcetable Pivot (Max(Score) for Question in ('+@listStr+')) as pivotable order by Franchise_Number,Store_Number,FiscalDate'

exec(@Sql)

答案 1 :(得分:0)

有两个错误,首先你必须在FROM之前和字符串内包含into#temp2子句。 如果要在#temp2中使用插入,则必须先定义表格