使用SQL Server进行动态数据透视查询

时间:2014-08-25 09:38:31

标签: sql sql-server pivot-table

我正在使用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'.

3 个答案:

答案 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

见: this SQLFiddle demo

答案 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;

请参阅此Demo in SQL Fiddle.

答案 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;

注意: 我试过这个,你检查一次。