SQL 查询错误(关键字 [=10= 附近的语法不正确。如果此语句是常见的 table 表达式...)

Error in SQL query (Incorrect syntax near the keyword 'with'. If this statement is a common table expression...)

我是这个网站的新手。我有一个 pivot 2 连接查询的查询。我在关键字 'with' 附近收到不正确的语法。如果此语句是一个常见的 table 表达式、xmlnamespaces 子句或更改跟踪上下文子句,则前一个语句必须以分号结尾。我一直在尝试输入分号,但仍然无法正常工作。

此处有相关查询。

Declare @sql nvarchar(max)
Declare @columns nvarchar(max)

declare @orgcols table(
[QuestionID] nvarchar(max)
)

insert into @orgcols
Select distinct a.[QuestionID] + ' -  ' + a.[GURSRVQ_TEXT] as [QuestionID]
from [MappingNew4] a 
left join [ICE_SURVEY_ANSWERS_MVCleaned] b
on a.[GUBSRVY_TITLE] = b.[GUBSRVY_TITLE]
join [ICE_SURVEY_ANSWERS_SUMMARY_MV] c
on b.[GUBSRVY_TITLE] = c.[GUBSRVY_TITLE]
where TERM = 'ABC';

;With combinedcolumntab as(
select distinct
STUFF((Select ','+[QuestionID]
from @orgcols T1
FOR XML PATH('')),1,1,'') as col from @orgcols T2
)
select @columns = col from combinedcolumntab

set @sql = N'With org as
(Select
b.TOKEN,a.[GUBSRVY_TITLE], a.[QuestionID] + '' -  '' + a.[GURSRVQ_TEXT] as [QuestionID] ,replace(replace((cast(b.[GURSRVQ_TEXT] as NVarchar(100))),'','','';''),'''''''','''''''''''') as[GURSRVQ_TEXT],(cast(isnull([GORSRVR_RESPONSE_1], 0) as int) 
+ cast(isnull([GORSRVR_RESPONSE_2],0) as int) + cast(isnull([GORSRVR_RESPONSE_3],0) as int) 
+ cast(isnull([GORSRVR_RESPONSE_4],0) as int) + cast(isnull([GORSRVR_RESPONSE_5],0) as int))
as RESPONSE
from [MappingNew4] a 
left join [ICE_SURVEY_ANSWERS_MVCleaned] b
on a.[GUBSRVY_TITLE] = b.[GUBSRVY_TITLE]
join [ICE_SURVEY_ANSWERS_SUMMARY_MV] c
on b.[GUBSRVY_TITLE] = c.[GUBSRVY_TITLE]
where TERM = ''ABC''
)
Select *
From Org
PIVOT
(
sum(RESPONSE)
FOR QuestionID
in ('+@columns+')
) as pvt'

EXECUTE sp_executesql @sql

用于插入 @orgcolsselect 语句,尝试将其更改为:

Select distinct quotename(a.[QuestionID] + ' -  ' + a.[GURSRVQ_TEXT]) as [QuestionID]

这修复了我得到的唯一错误并使其正常工作(尽管我猜测了一些关于 table 数据类型等的信息,因为你没有在你的问题中包含该信息...)