sqlsql-serversql-tuning

How to resolve datatype length difference errors while using unpivot in SQL Server?


I am running below SQL statements in SQL Server which is causing issues due to difference in length of the column types (name=nvarchar(100), address=nvarchar(250)).

select distinct  
    Id, Label, [Value]
from
    (select distinct 
         coalesce([Value], 'unknown') as Id,
         coalesce([Value], 'unknown') + ':' + I as label,
         coalesce([Value], 'unknown') as [Value]
     from 
         [dummyDB].[test].[test]
     unpivot
         ([Value] for I in (name, address)) as dataTable
    ) as t

Error:

Msg 8167, Level 16, State 1, Line 7
The type of column "address" conflicts with the type of other columns specified in the UNPIVOT list.

How to get this resolved?


Solution

  • If you use APPLY and VALUES to unpivot the data instead, you don't get this error. Using these tools is more versatile that the UNPIVOT operator anyway, so I personally prefer them:

    SELECT T.ID,
           V.Label,
           V.[Value]
    FROM dbo.Test T
         CROSS APPLY (VALUES('Name',T.Name),
                            ('Address',T.Address))V(Label,Value);
    

    If you have non string-type columns, you'll need to explicitly convert them (possibly with a style code):

    SELECT T.ID,
           V.Label,
           V.[Value]
    FROM dbo.Test T
         CROSS APPLY (VALUES('Name',T.Name),
                            ('Address',T.Address),
                            ('SomeDate',CONVERT(nvarchar(10),T.SomeDate,112)),
                            ('SomeInt',CONVERT(nvarchar(5),T.SomeInt)))V(Label,Value);