2016-12-07 60 views
0

有人可以帮助我解决此问题吗?我收到一个错误说与UNPIVOT列表中指定的其他列的类型冲突

与其他列 在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 '[email protected]+' 
       from unpiv 
       pivot 
       (
       max(value) 
       for col_name in ('[email protected]+') 
       ) piv' 

execute(@query) 

drop table #temp 
+2

downvotes和/或关闭请求的一个原因可能是,那*为什么我的代码不工作?*被明确地命名为第一点* *什么是不是** SO * [查看详细信息](http ://stackoverflow.com/help/on-topic) – Shnugo

+0

你可以添加CREATE TABLE语句和一些插入值吗? – McNets

+0

我可以建议你只显示最后的@query语句,不加引号吗? – McNets

回答

0

UNPIVOT不是反转数据的最佳方式。

将代码中的UNPIVOT部分替换为“CROSS APPLY WITH VALUES”,这是一种好得多的方法,它的实现效率更高,实现也更简单。