SQL 中的轴在空格处中断

Pivot in SQL is breaking on spaces

我正在 运行 进行查询以分析几个连接的 table 中的一些用户属性,并且工作正常,希望我的 header 被拆分space 由于它们在数据库中的价值。

这是我运行宁的查询:

DECLARE       @PivotColumns AS NVARCHAR(MAX),
              @query AS NVARCHAR(MAX)

select        @PivotColumns = STUFF((SELECT distinct ',' + QUOTENAME(Property_key) 
              from propertyentry where PROPERTY_KEY like 'jira.meta%'
                     and property_key not like '% %' -- removes tables with spaces in name, else won't pivot
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
              ,1,1,'')

set @query = 'SELECT id, user_name, first_name, last_name, ' +  @PivotColumns + ' from 
             (      
                                  select 
                                  --ps.id, cu.user_name, cu.first_name, cu.last_name, pe.property_key, cast(ps.propertyvalue as varchar(max)) as PV
                                  cu.user_name, cu.first_name, cu.last_name, ps.id, cast(ps.propertyvalue as varchar(max)) as PV, pe.property_key 
                                  from propertyentry pe 
                                  inner join propertystring ps
                                  on pe.id = ps.id 
                                  inner join external_entities ee
                                  on ee.ID = pe.entity_id
                                  inner join cwd_user cu
                                  on cu.user_name = ee.NAME
                                  ) x
            pivot 
            (
                           max(PV)
                           for property_key in (' + @PivotColumns + ')
            ) p 
                     order by 2,3,4'
execute(@query)

这会输出如下信息:(无法正确格式化为 table,抱歉)

|| id || user_name || first_name || last_name || meta.Laptop || meta.Kit || meta.PC ||

| 27076 | 0@emeastore | UK Store | Hove | NULL | NULL | 1234 |

| 27076 | 0@emeastore | UK Store | Hove | NULL | SPARE |    NULL |

| 27076 | 0@emeastore | UK Store | Hove | YES | NULL |  NULL |

我要将 "squishing" 行合并处理,没关系 - 我遇到的问题是其中一个 table 有字段 "meta.PC Asset" 而你可以看到,这就是 header.

中被拆分的内容

有没有一种方法可以 运行 相同的查询,但在 property_key 上,在 select 时将 spaces 替换为“_”?

那会给我这样的最终结果:

|| id || user_name || first_name || last_name || meta.Laptop || meta.Kit || meta.PC_Asset ||

| 27076 | 0@emeastore | UK Store | Hove | NULL | NULL | 1234 |

| 27076 | 0@emeastore | UK Store | Hove | NULL | SPARE |    NULL |

| 27076 | 0@emeastore | UK Store | Hove | YES | NULL |  NULL |

使用

SELECT @PivotColumns =
STUFF((SELECT DISTINCT ',' + REPLACE(QUOTENAME(LTRIM(RTRIM(Property_key))), ' ', '_') 
       FROM propertyentry
       WHERE PROPERTY_KEY LIKE 'jira.meta%'    
        FOR XML PATH(''), TYPE
        ).VALUE('.', 'NVARCHAR(MAX)') 
          ,1,1,'');

</code> 替换为 <code>_