在 SQL 服务器中使用 unpivot 时如何解决数据类型长度差异错误?
How to resolve datatype length difference errors while using unpivot in SQL Server?
我 运行 在 SQL 服务器中的 SQL 语句下面,由于列类型的长度差异(名称=nvarchar(100),地址=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
错误:
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.
如何解决这个问题?
如果您使用 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);
如果您有非 string-type 列,则需要显式转换它们(可能使用样式代码):
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);
我 运行 在 SQL 服务器中的 SQL 语句下面,由于列类型的长度差异(名称=nvarchar(100),地址=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
错误:
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.
如何解决这个问题?
如果您使用 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);
如果您有非 string-type 列,则需要显式转换它们(可能使用样式代码):
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);