xml为<option type =“x”> y </option>

时间:2015-12-04 12:05:21

标签: sql-server xml sql-server-2012

我有一个带属性的表

prodid  type    val
1       colour  red
1       size    large
2       colour  blue

我作为更大的查询的一部分制作了一个xml结构:

(SELECT type "@type",val  from t_prodattr pa where pa.prodid=product.id 
 FOR xml path('attribute'), root('attributes'), type),

给予

 <attributes>
    <attribute type="colour">
      <val>red</val>
    </attribute>
    <attribute type="size">
      <val>small</val>
    </attribute>
  </attributes>

我想要xml

<attributes>
    <attribute type="colour">red</attribute>
    <attribute type="size">small</attribute>
</attributes>

甚至

<attributes>
    <colour>red</colour>
    <size>small</size>
</attributes>

3 个答案:

答案 0 :(得分:2)

使用'*'作为val的别名。

SELECT type '@type',
       val as '*'  
from ...

Columns with a Name Specified as a Wildcard Character

更新

如果你想要type列中的元素名称,你必须通过连接字符串来构建XML。

declare @T table
(
  prodid int,
  type varchar(10),
  val varchar(10)
);

insert into @T values
(1,       'colour',  'red  '),
(1,       'size',    'la&ge'),
(2,       'colour',  'blue ');

select cast('<'+T.type+'>'+(select T.val as '*' for xml path(''))+'</'+T.type+'>' as xml)
from @T as T
for xml path(''), root('attributes'), type

结果:

<attributes>
  <colour>red  </colour>
  <size>la&amp;ge</size>
  <colour>blue </colour>
</attributes>

此部分(select T.val as '*' for xml path(''))负责为{x}等{1}}等XML特殊字符创建实体。

答案 1 :(得分:1)

<强>模式

DECLARE @t TABLE
  (
          [type]    VARCHAR(10) ,
          Val VARCHAR(10)
  )

INSERT  INTO @t
VALUES  ( 'colour', 'red' ),
        ( 'size', 'large' ),
        ( 'colours', 'blue' )

<强>查询

SELECT  type "@type" ,
        Val AS '*'
FROM    @t
FOR     XML PATH('attribute') ,
            ROOT('attributes') ,
            TYPE;

<强>输出

<attributes>
  <attribute type="colour">red</attribute>
  <attribute type="size">large</attribute>
  <attribute type="colours">blue</attribute>
</attributes>

答案 2 :(得分:1)

DECLARE @t TABLE (
    prodid INT,
    [type] VARCHAR(50),
    val VARCHAR(50)
)

INSERT INTO @t
VALUES
    (1, 'colour', 'red'),
    (1, 'size', 'large'),
    (2, 'colour', 'blue')

SELECT
    (
        SELECT [@type] = [type], [text()] = val
        FROM @t t2
        WHERE t2.prodid = t1.prodid
        FOR XML PATH('attribute'), root('attributes'), TYPE
    )
FROM (
    SELECT DISTINCT prodid
    FROM @t
) t1
FOR XML PATH('')

结果 -

<attributes>
  <attribute type="colour">red</attribute>
  <attribute type="size">large</attribute>
</attributes>
<attributes>
  <attribute type="colour">blue</attribute>
</attributes>