创建具有相同标记名称的Xml

时间:2016-09-23 13:01:58

标签: sql-server xml sql-server-2014

表名:样本

列名称: ID,名称

每一行用内部创建单独的标记。

显示像这样的Xml值

<Details>
     <id>1</id>
     <name>na</name>
     <Details>
       <id>2</id>
       <name>aa</name>
     </Details>
   </Details>

我试过这样但是它不起作用

select 
     id       'Details\id'
     ,name    'Details\name'
from sample

如何获取xml输出?

2 个答案:

答案 0 :(得分:2)

它是硬编码但应该有效:

DECLARE @x xml

SELECT @x = (
    SELECT x+''
    FROM (
        SELECT '%details?%id?'+CAST(id as nvarchar(max))+'%/id?%name?'+name+'%/name?' x
        FROM [sample] s
        UNION ALL
        SELECT  '%/details?'
        FROM [sample] s
        ) as t
    FOR XML PATH('')
)
SELECT CAST(REPLACE(REPLACE((CAST(@x as nvarchar(max))),'%','<'),'?','>') as xml)

[sample]表格中我得到了:

(1,'na'),
(2,'aa'),
(3,'sd')

输出:

<details>
  <id>1</id>
  <name>na</name>
  <details>
    <id>2</id>
    <name>aa</name>
    <details>
      <id>3</id>
      <name>sd</name>
    </details>
  </details>
</details>

修改

也可以通过递归CTE完成:

DECLARE @x xml

;WITH rec AS (
SELECT  CAST((
            SELECT TOP 1    id,
                            [name]
            FROM [sample]
            ORDER BY id DESC
            FOR XML PATH('details')
        ) as xml) as d,
        1 as [Level]
UNION ALL
SELECT  CAST((
            SELECT  id,
                    [name],
                    cast(r.d as xml)
            FROM [sample]
            WHERE s.id = id
            FOR XML PATH('details')
        ) as xml) as d,
        r.[Level]+1
FROM [sample] s
INNER JOIN rec r
    ON s.id = CAST(r.d.query('/details/id/text()') as nvarchar(max))-1
)

SELECT TOP 1 WITH TIES d
FROM rec
ORDER BY [Level] desc

相同的输出。

答案 1 :(得分:0)

您可以使用以下查询:

SELECT
    *,
    (SELECT
        *
    FROM #details
    WHERE id = 2
    FOR xml PATH ('Details'), TYPE)
FROM #details
WHERE id = 1
FOR xml PATH ('Details')

对于内循环,您可以使用CTE

表创建脚本:

CREATE TABLE #details (
    id int,
    name varchar(10)
)

INSERT INTO #details (id, name)
    VALUES (1, 'test'), (2, 'test2')