SQL Server XML文件与多个节点命名相同

时间:2016-08-03 16:08:43

标签: sql-server xml tsql cursor for-xml-path

我有这个内部XML,我将其传递给SQL Server存储过程。

Sample of XML being passed to SQL Server

正如您所看到的,它包含多个root个节点,但另外,它还可以包含1到' n' LotResults子节点数。

我是否可以在存储过程中操作此方法,以便为每个LotResults节点检索所有Result / root个节点?

到目前为止,我已经声明了可以处理顶级节点的cursor

DECLARE cur CURSOR FOR
   SELECT tab.col.value('ID[1]','NCHAR(10)') as INT_TransactionID,
          tab.col.value('ResultDateTime[1]','INT') as DAT_ResultDateTime,
          tab.col.value('StandardComment[1]/ID[1]','BIT') as INT_StandardCommentID,
          tab.col.value('ReviewComment[1]/ID[1]','BIT') as INT_ReviewCommentID
     FROM @XML_Results.nodes('/roots/root') AS tab(col)

     OPEN cur
-- loop over nodes within xml document and populate declared variables
    FETCH 
     NEXT 
     FROM cur

     INTO @INT_TransactionID, 
          @DAT_ResultDateTime, 
          @INT_StandardCommentID, 
          @INT_ReviewCommentID 

    WHILE @@FETCH_STATUS = 0
    BEGIN

    BEGIN
    -- use my values here

      END

    -- fetch next record
    FETCH 
     NEXT 
     FROM cur
     INTO @INT_TransactionID, 
          @DAT_ResultDateTime, 
          @INT_StandardCommentID, 
          @INT_ReviewCommentID 

      END

    CLOSE cur;

注意:我发现了一篇描述how to extract nodes with the same name的帖子,我觉得这可以用来实现我想要做的事情,但我需要一些关于如何将其应用于我的场景的指导。 / p>

1 个答案:

答案 0 :(得分:2)

没有游标!光标是由魔鬼创造的,导致可怜的小数据库人员远离基于集合思维的光线深入到黑暗的程序方法中......

请(以后的问题):不要粘贴图片!不得不在...中输入我的例子。

顺便说一下:你的在这里使用我的价值让你很难提出正确的建议。根据您在那里所做的事情,实际上可能需要一个游标。但在这种情况下,您应该从我向您展示的查询中创建光标......

试试这样:

DECLARE @xml XML=
'<roots>
  <root>
    <ID>5</ID>
    <LotResults>
      <ID>13</ID>
      <Result>
        <ID>5</ID>
        <Count>2</Count>
      </Result>
    </LotResults>
    <LotResults>
      <ID>13</ID>
      <Result>
        <ID>5</ID>
        <Count>2</Count>
      </Result>
    </LotResults>
    <StandardComment>
      <ID>0</ID>
    </StandardComment>
    <ReviewComment>
      <ID>0</ID>
    </ReviewComment>
  </root>
  <root>
    <ID>44</ID>
    <LotResults>
      <ID>444</ID>
      <Result>
        <ID>4444</ID>
        <Count>2</Count>
      </Result>
    </LotResults>
    <LotResults>
      <ID>555</ID>
      <Result>
        <ID>55</ID>
        <Count>2</Count>
      </Result>
    </LotResults>
    <StandardComment>
      <ID>5</ID>
    </StandardComment>
    <ReviewComment>
      <ID>5</ID>
    </ReviewComment>
  </root>
</roots>';

- 这是查询

SELECT r.value('ID[1]','int') AS root_ID
      ,lr.value('ID[1]','int') AS LotResult_ID
      ,lr.value('(Result/ID)[1]','int') AS LotResult_Result_ID
      ,lr.value('(Result/Count)[1]','int') AS LotResult_Result_Count
      ,r.value('(StandardComment/ID)[1]','int') AS StandardComment_ID 
      ,r.value('(ReviewComment/ID)[1]','int') AS ReviewComment_ID 
FROM @xml.nodes('/roots/root') AS A(r)
CROSS APPLY r.nodes('LotResults') AS B(lr)