SQL:递归更新 table 中的 xml 列

SQL: Update xml column in a table recursively

我在 sql 服务器 2012

中有一个 table

以下列定义

   CREATE TABLE [dbo].[tblStepList](
    [ToDoId] [int] IDENTITY(1,1) NOT NULL,
    [Data] [xml] NOT NULL
}

并且数据列是xml和

<Steplist>
  <Step>
    <StepId>e36a3450-1c8f-44da-b4d0-58e5bfe2a987</StepId>
    <Rank>1</Rank>
    <IsComplete>false</IsComplete>
    <TextReadingName>bug-8588_Updated3</TextReadingName>     
  </Step>
  <Step>
    <StepId>4078c1b1-71ea-4578-ba61-d2f6a5126ba1</StepId>
    <Rank>2</Rank>
    <TextReadingName>reading1</TextReadingName>
  </Step>
</Steplist>'

我想用我的新 xml 更新 table 的每一行,以便在 TextReading 名称

之后查看名为 TextReadingId 的新节点

我想插入一个名为 TextReadingId 的新节点我希望我的 TextReadingId 值为 运行 数字,如下所示

 <Steplist>
          <Step>
            <StepId>e36a3450-1c8f-44da-b4d0-58e5bfe2a987</StepId>
            <Rank>1</Rank>
            <IsComplete>false</IsComplete>
            <TextReadingName>bug-8588_Updated3</TextReadingName>    
          <TextReadingId>1</TextReadingId>   
          </Step>
          <Step>
            <StepId>4078c1b1-71ea-4578-ba61-d2f6a5126ba1</StepId>
            <Rank>2</Rank>
            <TextReadingName>reading1</TextReadingName>
          <TextReadingId>1</TextReadingId> 
          </Step>
        </Steplist>';

这是我尝试过的方法,但没有按预期工作

DECLARE @i int;

SELECT

@i = s.data.value('count(/Steplist/Step)', 'nvarchar(max)')

FROM tblStepList   s

SET data.modify('insert <TextReadingId>{sql:variable("@i")}</TextReadingId> as last into (/Steplist/Step[sql:variable("@i")])[1]')

print @i
End

请尝试以下解决方案。

它正在使用 XQuery 及其 FLWOR 表达式。

SQL

USE tempdb;
GO

DROP TABLE IF EXISTS [dbo].[tblStepList];

CREATE TABLE [dbo].[tblStepList](
    [ToDoId] [int] IDENTITY(1,1) NOT NULL,
    [Data] [xml] NOT NULL
);

INSERT INTO dbo.tblStepList ([Data]) VALUES
(N'<Steplist>
  <Step>
    <StepId>e36a3450-1c8f-44da-b4d0-58e5bfe2a987</StepId>
    <Rank>1</Rank>
    <IsComplete>false</IsComplete>
    <TextReadingName>bug-8588_Updated3</TextReadingName>     
  </Step>
  <Step>
    <StepId>4078c1b1-71ea-4578-ba61-d2f6a5126ba1</StepId>
    <Rank>2</Rank>
    <TextReadingName>reading1</TextReadingName>
  </Step>
</Steplist>');

-- before
SELECT * FROM dbo.tblStepList;

UPDATE dbo.tblStepList
SET [Data]  = [Data].query('<Steplist>
{
    for $x in /Steplist/Step
    let $pos := count(Steplist/*[. << $x]) + 1
    return <Step>{$x/*,
        if (not($x/TextReadingId)) then <TextReadingId>{$pos}</TextReadingId>
        else ()} 
        </Step>
}
</Steplist>');

-- after
SELECT * FROM dbo.tblStepList;