如何将 sql:column() 插入到 xml

How to insert sql:column() to xml

鉴于此 xml

    <items>
  <item>
    <position>2</position>
    <code>123-122</code>
    <description>Circulator 5GPM</description>
  </item>
  <item>
    <position>4</position>
    <code>124-128</code>
    <description>Circulator 25GPM</description>
  </item>
</items>

我想从关系 table 中插入值,例如

最好使用 T-Sql sql:column("position") 等..

我该怎么做?

您可以像这样 insert 将新节点 xml

DECLARE @xml XML = '<items>
  <item>
    <position>2</position>
    <code>123-122</code>
    <description>Circulator 5GPM</description>
  </item>
  <item>
    <position>4</position>
    <code>124-128</code>
    <description>Circulator 25GPM</description>
  </item>
</items>'

DECLARE @SampleData AS TABLE
(
    position int,
    code varchar(20),
    [description] varchar(100)
)
INSERT INTO @SampleData
VALUES 
(1,'123-123','description 1'),
(2,'124-124','description 2')


DECLARE @NewXmlNode XML =
(
    SELECT * 
    FROM @SampleData
    FOR XML PATH('item'),TYPE
)
SELECT @xml, @NewXmlNode

SET @xml.modify('
    insert sql:variable("@NewXmlNode") as last into (/items)[1]
')

结果:

<items>
  <item>
    <position>2</position>
    <code>123-122</code>
    <description>Circulator 5GPM</description>
  </item>
  <item>
    <position>4</position>
    <code>124-128</code>
    <description>Circulator 25GPM</description>
  </item>
  <item>
    <position>1</position>
    <code>123-123</code>
    <description>description 1</description>
  </item>
  <item>
    <position>2</position>
    <code>124-124</code>
    <description>description 2</description>
  </item>
</items>