如何使用动态查询插入表变量?

时间:2015-06-17 12:41:55

标签: sql sql-server-2008

我尝试使用临时表来开发这个存储过程,但这不起作用所以我切换到使用表变量。我需要对表变量执行临时动态查询,然后使用该表变量来执行最终查询。问题是我收到错误"必须声明标量变量@ clms"。我假设Exec没有表变量的范围?

DECLARE @qry nvarchar(4000)
DECLARE @clms TABLE (mastcatname nvarchar(50),engdtlbeta decimal (18,4))
SET @qry='INSERT INTO @clms 
          SELECT distinct replace(mastcatname, '' '', '''') as mastcatname, 
                 engdtlbeta 
          FROM vw_Scorecard 
          WHERE empsurveyid=' + cAST(@EmpSurveyID AS nvarchar(10)) + ' 
               AND UnitID IN (' + @UnitIDs + ') 
          ORDER BY engdtlbeta desc, MastCatName'

EXEC(@qry)

DECLARE @cols nvarchar(1000)
SELECT @cols=COALESCE (@cols + ',[' + mastcatname + ']', '[' + mastcatname + ']') 
FROM @clms


SET @qry='SELECT UnitName ,
                 ParentName, ' + @cols + ' 
          FROM (
                SELECT UnitName,
                    ParentName, 
                    ScoreAvg, 
                    replace(mastcatname, '' '','''') as mastcatname 
                FROM vw_Scorecard 
                WHERE UnitID IN (' + @UnitIDs + ') 
                    AND EmpSurveyID=' + cast(@EmpSurveyID as nvarchar(5)) + ' ) p
          PIVOT
            (SUM(ScoreAvg) FOR mastcatname in (' + @cols + ')) as pvt'

EXEC (@qry)

2 个答案:

答案 0 :(得分:15)

这是一个简单的最小例子。您可以使用INSERT EXEC语句。关键是在动态查询的内部和外部声明表变量。在动态查询结束时,只需从表变量中选择并将结果集插入外部表变量:

DECLARE @t TABLE ( id INT ) 

DECLARE @q NVARCHAR(MAX) = 'declare @t table(id int) 
                            insert into @t values(1),(2) 
                            select * from @t'

INSERT INTO @t
EXEC(@q)

SELECT * FROM @t

答案 1 :(得分:0)

我发现这种尝试基本上可以做同样的事情。我更改了SQL,是的,它有效!但是后来我想,这使事情变得过于复杂。为什么在动态SQL中声明表变量,插入然后全选?为什么不选择...

DECLARE @t TABLE ( id INT ) 

DECLARE @q NVARCHAR(MAX) = 'select 1 union select 2'

INSERT INTO @t
EXEC(@q)

SELECT * FROM @t