使用FLWOR从另一个表中获取数据

2022-04-02 00:00:00 xquery sql-server xquery-sql flwor

我在SQL Server 2012中有一个表,其结构如下:

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

Data列的类型为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更新表的每一行,以便在TextReadingID之后查找名为TextReadingID的新节点

我有一个二级表,其中包含文本读取值steid和textreadingid

StepId                                TextReadingId 
---------------------------------------------------
e36a3450-1c8f-44da-b4d0-58e5bfe2a987    118
4078c1b1-71ea-4578-ba61-d2f6a5126ba1    119
d466a8ee-9214-4b9c-94f9-2117f5dffe93    401

并且我希望我的TextReadingId值来自上表

 <Steplist>
          <Step>
            <StepId>e36a3450-1c8f-44da-b4d0-58e5bfe2a987</StepId>
            <Rank>1</Rank>
            <IsComplete>false</IsComplete>
            <TextReadingName>bug-8588_Updated3</TextReadingName>    
          <TextReadingId>118</TextReadingId>   
          </Step>
          <Step>
            <StepId>4078c1b1-71ea-4578-ba61-d2f6a5126ba1</StepId>
            <Rank>2</Rank>
            <TextReadingName>reading1</TextReadingName>
          <TextReadingId>401</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

Here is another answer that helped but it does not join with my other table for the results


解决方案

最简单的方法是重建每个Step节点,然后使用FOR XML将其聚合起来

在相关子查询中,我们执行以下操作:

  • 使用.nodes()拆分Step节点
  • StepId节点值上的左联接StepReading
  • 创建包含新Step节点的未命名列...
  • .它包含使用./*...
  • 的现有对象的所有子对象
  • .和一个额外的子节点TextReadingId,其值来自StepReading
  • 然后使用FOR XML
  • 聚合备份
UPDATE sl
SET Data = (
    SELECT v.Step.query('
<Step>{./*,
        if (not(./TextReadingId)) then
            <TextReadingId>{sql:column("sr.TextReadingId")}</TextReadingId>
        else ()
        }
</Step>
    ')
    FROM sl.Data.nodes('/Steplist/Step') v(Step)
    LEFT JOIN StepReading sr ON sr.StepId = v.Step.value('(StepId/text())[1]','uniqueidentifier')
    FOR XML PATH(''), ROOT('Steplist'), TYPE
)
FROM tblStepList sl;

SQL Fiddle

相关文章