I tried to develop this stored procedure using a temp table but that wouldn't work so I switched to using a table variable. I need to execute an interim dynamic query into the table variable and then I use that table variable to execute the final query. The problem is that I receive an error "must declare scalar variable @clms". I assume that Exec doesn't have scope for the table variable?
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)
sp_executesqlwith parameters@UnitIDscome from? Could you put those values into another table variable? Then you wouldn't need dynamic SQL for the first query.