我对SQL查询不是很熟悉。最近我尝试使用SQL Server的unpivot
功能构建查询,但我遇到的错误是:
列“U_ItemModality”的类型与其他类型冲突 UNPIVOT列表中指定的列。
这是我的问题:
select
cast(unpvt.ItemCode collate database_default AS VARCHAR(30)) as ItemCode,
cast(unpvt.attribute collate database_default AS VARCHAR(30)) as attribute,
cast(unpvt.value collate database_default AS VARCHAR(30)) as value
from [OITM]
unpivot (
value for attribute in (U_Mfg_Part_Num, U_Part_Descriptor, U_ItemModality)
) unpvt
inner join [@AECTRANDATA] as WI
on unpvt.ItemCode = WI.U_ObjectKeyValue
inner join OITM AS IM
on WI.U_ObjectKeyValue = IM.ItemCode
where
WI.U_ObjectType ='4'
在此查询中,如果我删除u_itemmodality
,它将会运行。其他两列的大小为100
字符,但此列的大小为30
字符。
如何克服这种情况?
答案 0 :(得分:0)
使用UNPIVOT
时,数据类型的长度必须相等。有关详细信息,请参阅此question。您应该将U_ItemModality
转换为VARCHAR(100)
,以使其与其他两列的长度相同。
select
cast(unpvt.ItemCode collate database_default AS VARCHAR(30)) as ItemCode,
cast(unpvt.attribute collate database_default AS VARCHAR(30)) as attribute,
cast(unpvt.value collate database_default AS VARCHAR(30)) as value
from (
select
U_Mfg_Part_Num,
U_Part_Descriptor,
U_ItemModality = convert(varchar(100), U_ItemModality)
from [OITM]
)t
unpivot (
value for attribute in (U_Mfg_Part_Num, U_Part_Descriptor, U_ItemModality)
) unpvt
inner join [@AECTRANDATA] as WI
on unpvt.ItemCode = WI.U_ObjectKeyValue
inner join OITM AS IM
on WI.U_ObjectKeyValue = IM.ItemCode
where
WI.U_ObjectType ='4'