有人可以帮我解决这个问题吗?我收到错误说
列的类型"名称"与其他列的类型冲突 在UNPIVOT清单
中指定
我试图将名称转换为varchar
,但没有任何效果。
;with hd (id, name, parentid, category)
as
(
select CAPABILITY_COMPONENT_ID id, CAPABILITY_COMPONENT_NAME name, CAPABILITY_PARENT_ID as parentid, 1 as category
from [dbo].[TDM_FCT_CPBLITY]
where CAPABILITY_PARENT_ID = -1
union all
select t1.CAPABILITY_COMPONENT_ID, t1.CAPABILITY_COMPONENT_NAME, t1.CAPABILITY_PARENT_ID, hd.category +1
from [dbo].[TDM_FCT_CPBLITY] t1
inner join hd
on t1.CAPABILITY_PARENT_ID = hd.id
)
select category categoryNumber
into #temp
from hd
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + quotename('cat_'+cast(categoryNumber as varchar(10))+'_'+col)
from #temp
cross apply (select 'id' col
union all
select 'name' col) src
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = ';with hd (id, name, parentid, category)
as
(
select CAPABILITY_COMPONENT_ID as id, CAPABILITY_COMPONENT_NAME as name, CAPABILITY_PARENT_ID as parentid, 1 as category
from [dbo].[TDM_FCT_CPBLITY]
where CAPABILITY_PARENT_ID = -1
union all
select t1.CAPABILITY_COMPONENT_ID, t1.CAPABILITY_COMPONENT_NAME, t1.CAPABILITY_PARENT_ID, hd.category +1
from [dbo].[TDM_FCT_CPBLITY] t1
inner join hd
on t1.CAPABILITY_PARENT_ID = hd.id
),
unpiv as
(
select value, ''cat_''+cast(category as varchar(5))+''_''+ col col_name
from
(
select cast(id as varchar(17)) id, name, parentid, category
from hd
) src
unpivot
(
value for col in (id, name)
) un
)
select '+@cols+'
from unpiv
pivot
(
max(value)
for col_name in ('+@cols+')
) piv'
execute(@query)
drop table #temp
答案 0 :(得分:0)
UNPIVOT不是取消数据存储的最佳方式。
将代码的UNPIVOT部分替换为" CROSS APPLY WITH VALUES"这是一个更好的方法,它更有效,实施起来也更简单。