SQL 服务器 - 根据数据输出 XML 节点结构

SQL Server - output of XML node structure as per data

为此请求帮助:我有一个要求,其中 xml 输出需要低于所需的格式。主要障碍是获取动态 xml 节点 <Shares1_1>,即关键字 'Shares' 与列共享和 ID 中的数据连接。

期望的输出:

当前table结构和数据:

DROP TABLE IF EXISTS #TMP
CREATE TABLE #TMP(ID smallint, Shares VARCHAR(50), Name VARCHAR(50))

INSERT INTO #TMP(ID, Shares, Name) 
VALUES (1,1,'John'), (2,1,'Tim'), (3,2,'Miles')

select * from #tmp

我尝试获取输出(不正确)

declare @xml xml 
select @xml =(
    
        select ID, Shares, Name
        from #tmp
        for xml path ('snap'),elements, xsinil, type
)
select @xml

提前感谢大家对此的调查。

干杯。

SQL 服务器在设计上是声明式的。您将不得不使用 Dynamic SQL 或一些字符串操作。

例子

Declare @S varchar(max) = ''

Select @S=@S+concat('<Shares',Shares,'_',ID,'>',B.XML,'</Shares',Shares,'_',ID,'>')
 From #tmp A
 Cross Apply ( Select A.* for XML path('') ) B(xml)

Declare @XML xml = convert(xml,concat('<Snap>',@S,'</Snap>'))
Select @XML

结果

<Snap>
  <Shares1_1>
    <ID>1</ID>
    <Shares>1</Shares>
    <Name>John</Name>
  </Shares1_1>
  <Shares1_2>
    <ID>2</ID>
    <Shares>1</Shares>
    <Name>Tim</Name>
  </Shares1_2>
  <Shares2_3>
    <ID>3</ID>
    <Shares>2</Shares>
    <Name>Miles</Name>
  </Shares2_3>
</Snap>