Indeed. However looking I can't see any reason why this is dynamic SQL at all.
This should work just fine
DECLARE @TreatyNumber As Varchar(20)
SET @TreatyNumber = '200704.2.6'
DECLARE @temp_provisions As Table (
TreatyNum Varchar(20),
topic Varchar(100),
Subtopic Varchar(100),
SurveyQuestion Varchar(100),
SurveyPart Varchar(5),
ColName Varchar(100)
)
INSERT INTO @temp_provisions (TreatyNum, topic, Subtopic, SurveyQuestion, SurveyPart, ColName)
SELECT vwT.TreatyNumber, topics.PieceTitle AS topic, subsection.PieceTitle AS Subtopic, question.PieceTitle AS SurveyQuestion,
(CONVERT(Varchar, topics.PieceNumber) + CONVERT(Varchar, subsection.PieceNumber)) AS PartID,
SAP.ColumnName
FROM Treaty.vwTreaty AS vwT
INNER JOIN Survey.vwSurveyInstance AS vwSI ON vwT.TreatySurveyInstanceId = vwSI.SurveyInstanceId
INNER JOIN Survey.vwSurveyTemplate AS vwST ON vwSI.SurveyInstanceSurveyTemplateId = vwST.SurveyTemplateId
INNER JOIN Survey.vwSurveyPiece topics ON vwST.SurveyTemplateId = topics.SurveyPieceSurveyTemplateId
AND topics.SurveyPieceTypeIdCodeName = 'Topic'
INNER JOIN Survey.vwSurveyPiece AS subsection ON subsection.ParentSurveyPieceId = topics.SurveyPieceId
AND subsection.SurveyPieceTypeIdCodeName = 'Topic Subsection'
INNER JOIN Survey.vwSurveyPiece AS question ON question.ParentSurveyPieceId = subsection.SurveyPieceId
AND question.SurveyPieceTypeIdCodeName = 'Question'
INNER JOIN Survey.SurveyAnswerPart SAP ON question.SurveyPieceId = SAP.SurveyPieceId
WHERE vwT.TreatyNumber = @TreatyNumber
I've removed the order by as, unless there's an identity column on the table, the order of rows inserted is meaningless. Order by should be used on the select that reads from the table variable.
Gail Shaw
Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability