I am trying to run an UNPIVOT statement from a stored procedure, on a table in a different database. I can run the UNPIVOT fine locally, but when I run it on a different database/server I get the following error.
The type of column "XXX" conflicts with the type of other columns specified in the UNPIVOT list.
Here is a slimmed down version of my UNPIVOT.
CREATE TABLE temp (
id nvarchar(100),
F1 nvarchar(100),
F2 nvarchar(100),
F3 decimal(5,0)
)
INSERT INTO temp VALUES(N'100', N'111', N'AAA', 123)
INSERT INTO temp VALUES(N'100', N'222', N'BBB', 456)
INSERT INTO temp VALUES(N'100', N'333', N'CCC', 789)
INSERT INTO temp VALUES(N'100', N'444', N'DDD', 012)
INSERT INTO temp VALUES(N'100', N'555', N'EEE', 345)
SELECT * FROM ( SELECT
ID,
CAST(F1 AS NVARCHAR(MAX)) AS F1,--used in order to normalize the data
CAST(F2 AS NVARCHAR(MAX)) AS F2,--used in order to normalize the data
CAST(F3 AS NVARCHAR(MAX)) AS F3--used in order to normalize the data
FROM
TEMP ) AS T UNPIVOT(FieldValue for FieldName in ( F1, F2, F3 )) AS UNPVT
I did notice that this error occurs when the table I am UNPIVOTing, has DECIMAL() field types.
As always, any help is appreciated.
Update: It appears that creating a view on the remote server will allow for the CAST to occur properly. But why? I also tried using cte, but that did not work. I wanted to avoid creating views. Hopefully that is not the only solution.
The error
is very obvious and one of the better messages. It tells you that your UNPIVOT list contains columns of different types. Here’s an example that causes such an error: SQL Fiddle
On a local query, given your query as-written in your question SQL Fiddle, it cannot possibly elicit this error since you have already CAST all the columns as NVARCHAR(MAX).
However, on a remote query, it appears that SQL Server fails the query at compile time. It seems to pre-validate the pivot columns prior to CAST – seemingly because it may be possible to perform the CAST locally and at a different point in the execution flow. The workaround to this appears to be creating a VIEW that will resolve the CASTs on the remote server.
Workaround
You can force the query to resolve remotely (tested on 2005 as the remote server as minimum) using FOR XML, which has the benefit that the values will be extracted back using
nvarchar(max)anyway for conformity.SQLKiwi found that using sql_variant as the CAST target makes the remote query work, as shown in the chat transcript here.