从表中存储的xml值命名列别名

时间:2017-07-31 10:18:35

标签: sql sql-server xml alias

我正在尝试根据另一个表中的xml值命名别名。该值由用户定义,因此无法静态命名。

表(table1)和列(TimeBuckets)中的XML:

<buckets>
  <bucket id="1" name="Overnight to 3 Mths">
    <lower>0</lower>
    <upper>3</upper>
  </bucket>
</buckets>

我想根据table1中的'name'在select语句中设置列的别名。

我可以使用xml路径选择名称值,如下所示:

table1.TimeBucket.value( '(buckets/bucket/@name)[1]', 'nvarchar(255)' )

我目前有以下SQL查询,但它不允许我这样定义别名:

select 'test' as (table1.TimeBucket.value( '(buckets/bucket/@name)[1]', 'nvarchar(255)' )
from table1

2 个答案:

答案 0 :(得分:1)

因为列名在编译时解析而不是在SQL语句的运行时解析,所以只有动态sql可以这样做:

declare @columnName as varchar(255);
SELECT @columnName = TimeBucket.value( '(buckets/bucket/@name)[1]', 'nvarchar(255)' )
    FROM table1
    WHERE ID = 1; -- if you have more than one record in table1

declare @sql nvarchar(max);
set @sql = 'select ''test'' as [' + replace(@columnName, '''', '''''') + '] from table1;'

exec sp_executesql @sql;

答案 1 :(得分:0)

两种方法:

declare @table1 table (TimeBucket xml)
insert into @table1
values('<buckets>
  <bucket id="1" name="Overnight to 3 Mths">
    <lower>0</lower>
    <upper>3</upper>
  </bucket>
</buckets>')

select test = t.TimeBucket.value( '(buckets/bucket/@name)[1]', 'nvarchar(255)' ),
              t.TimeBucket.value( '(buckets/bucket/@name)[1]', 'nvarchar(255)' ) as test
from @table1 t