在SQLServer中使用unpivot时,如何解决数据类型长度差异错误?

efzxgjgh  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(646)

我在SQLServer中运行下面的sql语句,这是由于列类型(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

错误:
消息8167,16级,状态1,第7行
列“address”的类型与unpivot列表中指定的其他列的类型冲突。
如何解决这个问题?

kfgdxczn

kfgdxczn1#

如果你使用 APPLY 以及 VALUES 如果要取消打印数据,则不会出现此错误。使用这些工具比 UNPIVOT 不管怎样,我个人更喜欢他们:

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

如果有非字符串类型的列,则需要显式转换它们(可能使用样式代码):

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

相关问题