0

I am creating a dynamic pivot query using SQL Server 2008 but got stuck in STUFF.

Example:

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;

Error

 Incorrect syntax near the keyword 'order'.

3 Answers 3

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)
;

not exec @col

see: this SQLFiddle demo

Sign up to request clarification or add additional context in comments.

Comments

1

Meem, I have modified your query and it should look like this.

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;

See this Demo in SQL Fiddle.

Comments

-1

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;

Note: i tried this and u check it once.

2 Comments

If I do so then again error Incorrect syntax near ' + @tablename + '.
add '' to QUOTENAME(cola)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.