我正在使用SQL Server 2008创建动态数据透视查询,但卡在STUFF
。
示例:
Declare @col as nvarchar(max)
Declare @tablename as nvarchar(max)
SET @col = 'STUFF((SELECT '','' + QUOTENAME(cola)
from ' + @tablename + '
group by cola
order by cola
FOR XML PATH(''''), TYPE
).value(''.'', ''NVARCHAR(MAX)'')
,1,1,'''')'
execute(@col)
print @col;
错误
Incorrect syntax near the keyword 'order'.
答案 0 :(得分:1)
Declare @col as nvarchar(max)
Declare @tablename as nvarchar(max) = N'Table1'
set @col = N'SELECT
STUFF((
SELECT
'','' + QUOTENAME(cola)
FROM ' + @tablename + N'
GROUP BY
cola
ORDER BY
cola
FOR xml PATH (''''), TYPE
)
.value(''.'', ''NVARCHAR(MAX)''), 1, 1, '''');'
execute(@col)
;
不是exec @col
答案 1 :(得分:1)
Meem,我修改了你的查询,看起来应该是这样的。
Declare @col as nvarchar(max)
Declare @tablename as nvarchar(max)
set @col = 'REF_REFM_CODE'
set @tablename = 'tblKeywords'
SET @col = 'Select STUFF((SELECT ' + ''','' + ' + @col + '
from ' + @tablename + '
group by ' + @col +
' order by ' + @col +
' FOR XML PATH(''''), TYPE
).value(''.'', ''NVARCHAR(MAX)'')
,1,1,'''')'
execute(@col)
print @col;
答案 2 :(得分:-1)
将@col声明为nvarchar(max) 将@tablename声明为nvarchar(max)
SET @col =' STUFF((SELECT'','' + QUOTENAME(可乐) 来自'' + @tablename +''' 可乐集团 由可乐订购 FOR XML PATH(''''),TYPE ).value(''。'','' NVARCHAR(MAX)'') ,1,1,'''')' 执行(@col)
print @col;
注意强>: 我试过这个,你检查一次。