Having a datatype problem with SQL Server dynamic pivot

65 Views Asked by At

Datatype problem with a SQL Server dynamic pivot query.

UPDATE: code works properly now by using datatype nvarchar(MAX) for both @cols and @query. Thanks for the input those who did.


I'm trying to create a SQL Server dynamic pivot query so I don't need to explicitly name all columns in the query statement (there will be 323 columns in the pivoted table and those might change from time to time).

I've build my pivot attempt off another example here in Stack Overflow, but I'm apparently having trouble with the datatypes. I'm not sure how to resolve the issue, so I'd appreciate some input if you can help with a solution.

For background, the source table MyTable to be pivoted contains the columns and datatypes seen in the screenshot below (left side). A sample of a 'select *' query result of that table is seen in image below (right side).

MyTable & Query

The SQL query code that I've used to try to create a dynamic pivot is shown here (corrected):

DECLARE @cols AS nvarchar(255),
        @query AS nvarchar(255);

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.attKey) 
                   FROM MyTable c
                   FOR XML PATH(''), TYPE).value('.', 'varchar(255)'), 1, 1, '')

set @query = 'SELECT landingId, ' + @cols + ' from 
            (
                select landingId
                    , attValue
                    , attKey
                from MyTable
           ) x
            pivot 
            (
                 max(attValue)
                for attKey in (' + @cols + ')
            ) p '

execute(@query)

I get this error from SSMS when executing:

Msg 8114, Level 16, State 5, Line 5
Error converting data type varchar to real.

Any ideas? Thanks in advance. BT

0

There are 0 best solutions below