Передача счетчика в SQL-запрос содержимого XML, NULL-ответ, но жесткое кодирование выбирает значение - PullRequest
0 голосов
/ 25 апреля 2018

Я запрашиваю содержимое XML в таблице в SQL Server 2014 с пакетом обновления 2 GDR.Я могу сосчитать нужные узлы и выбрать конкретный узел, но я должен динамически собирать нужные значения узлов.Пожалуйста, перенаправьте меня на правильный синтаксис и / или метод для этого.

Вместо восьми значений, которые я ожидал от подсчета, я получаю только то значение @loops, которое напечатано .

Ниже приведен базовый код:

DECLARE @x  XML

SET @x = 

     '<ArrayOfOrderedRequest xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/NewWorld.Aegis.Cad.Common.Broker.Contract.ResponsePlans">
  <OrderedRequest>
    <Request i:type="RequestWithResource">
      <BackupList>
        <RequestBackup>
          <Request i:type="RequestWithResource">
            <NodeID>f1e00f33-0451-4b25-b69a-6c5f6e358fa6</NodeID>
            <Quantity>1</Quantity>
            <Action>Dispatch</Action>
            <Resource>
              <ID>160</ID>
              <ResourceType>1</ResourceType>
            </Resource>
          </Request>
          <Sequence>0</Sequence>
        </RequestBackup>
      </BackupList>
      <NodeID>7b901b61-5c7b-4429-a306-d42f7b367e14</NodeID>
      <Quantity>1</Quantity>
      <Action>Dispatch</Action>
      <Resource>
        <ID>3989</ID>
        <ResourceType>2</ResourceType>
      </Resource>
    </Request>
    <Sequence>1</Sequence>
  </OrderedRequest>
  <OrderedRequest>
    <Request i:type="RequestWithResource">
      <BackupList>
        <RequestBackup>
          <Request i:type="RequestWithResource">
            <NodeID>e4eedaf1-3a7e-4bb5-824c-84efebcab2dd</NodeID>
            <Quantity>1</Quantity>
            <Action>Dispatch</Action>
            <Resource>
              <ID>164</ID>
              <ResourceType>1</ResourceType>
            </Resource>
          </Request>
          <Sequence>0</Sequence>
        </RequestBackup>
      </BackupList>
      <NodeID>1df4b869-5ec8-4582-91f6-28c174aa99ed</NodeID>
      <Quantity>1</Quantity>
      <Action>Dispatch</Action>
      <Resource>
        <ID>3988</ID>
        <ResourceType>2</ResourceType>
      </Resource>
    </Request>
    <Sequence>2</Sequence>
  </OrderedRequest>
  <OrderedRequest>
    <Request i:type="RequestWithResource">
      <NodeID>f30cd65e-5919-44a5-9977-6e04db9a738b</NodeID>
      <Quantity>1</Quantity>
      <Action>Dispatch</Action>
      <Resource>
        <ID>3991</ID>
        <ResourceType>2</ResourceType>
      </Resource>
    </Request>
    <Sequence>3</Sequence>
  </OrderedRequest>
  <OrderedRequest>
    <Request i:type="RequestWithResource">
      <BackupList>
        <RequestBackup>
          <Request i:type="RequestWithResource">
            <NodeID>1df52ab3-ea2f-45e8-af34-f651625cd1ca</NodeID>
            <Quantity>1</Quantity>
            <Action>Dispatch</Action>
            <Resource>
              <ID>124</ID>
              <ResourceType>1</ResourceType>
            </Resource>
          </Request>
          <Sequence>0</Sequence>
        </RequestBackup>
      </BackupList>
      <NodeID>4d1224ee-998d-48e9-8c9c-a74762d0c944</NodeID>
      <Quantity>1</Quantity>
      <Action>Dispatch</Action>
      <Resource>
        <ID>3994</ID>
        <ResourceType>2</ResourceType>
      </Resource>
    </Request>
    <Sequence>4</Sequence>
  </OrderedRequest>
  <OrderedRequest>
    <Request i:type="RequestWithResource">
      <BackupList>
        <RequestBackup>
          <Request i:type="RequestWithResource">
            <NodeID>fee1da03-f490-423d-bdcc-aa7195d560a0</NodeID>
            <Quantity>1</Quantity>
            <Action>Dispatch</Action>
            <Resource>
              <ID>160</ID>
              <ResourceType>1</ResourceType>
            </Resource>
          </Request>
          <Sequence>0</Sequence>
        </RequestBackup>
      </BackupList>
      <NodeID>6c4209fe-9d8c-48fd-8f9f-6a38299ac368</NodeID>
      <Quantity>1</Quantity>
      <Action>Dispatch</Action>
      <Resource>
        <ID>4846</ID>
        <ResourceType>2</ResourceType>
      </Resource>
    </Request>
    <Sequence>5</Sequence>
  </OrderedRequest>
  <OrderedRequest>
    <Request i:type="RequestWithResource">
      <BackupList>
        <RequestBackup>
          <Request i:type="RequestWithResource">
            <NodeID>41ccb2b1-0e6c-4a54-b1bd-ab22152cdd6b</NodeID>
            <Quantity>1</Quantity>
            <Action>Dispatch</Action>
            <Resource>
              <ID>164</ID>
              <ResourceType>1</ResourceType>
            </Resource>
          </Request>
          <Sequence>0</Sequence>
        </RequestBackup>
      </BackupList>
      <NodeID>218da0c7-fdd1-4e20-a62b-feba25a28095</NodeID>
      <Quantity>1</Quantity>
      <Action>Dispatch</Action>
      <Resource>
        <ID>4844</ID>
        <ResourceType>2</ResourceType>
      </Resource>
    </Request>
    <Sequence>6</Sequence>
  </OrderedRequest>
  <OrderedRequest>
    <Request i:type="RequestWithResource">
      <BackupList>
        <RequestBackup>
          <Request i:type="RequestWithResource">
            <NodeID>f86419eb-177f-4e3f-bdc2-6d8fd1e3f123</NodeID>
            <Quantity>1</Quantity>
            <Action>Dispatch</Action>
            <Resource>
              <ID>160</ID>
              <ResourceType>1</ResourceType>
            </Resource>
          </Request>
          <Sequence>0</Sequence>
        </RequestBackup>
      </BackupList>
      <NodeID>d588e812-1607-49a7-b1af-20c3c998a8a6</NodeID>
      <Quantity>1</Quantity>
      <Action>Dispatch</Action>
      <Resource>
        <ID>4538</ID>
        <ResourceType>2</ResourceType>
      </Resource>
    </Request>
    <Sequence>7</Sequence>
  </OrderedRequest>
  <OrderedRequest>
    <Request i:type="RequestWithResource">
      <BackupList>
        <RequestBackup>
          <Request i:type="RequestWithResource">
            <NodeID>dd71e9bb-4d92-47a1-b325-e2e0ed6b7405</NodeID>
            <Quantity>1</Quantity>
            <Action>Dispatch</Action>
            <Resource>
              <ID>164</ID>
              <ResourceType>1</ResourceType>
            </Resource>
          </Request>
          <Sequence>0</Sequence>
        </RequestBackup>
      </BackupList>
      <NodeID>3e125708-28ba-4629-b096-d565030cb5c2</NodeID>
      <Quantity>1</Quantity>
      <Action>Dispatch</Action>
      <Resource>
        <ID>4277</ID>
        <ResourceType>2</ResourceType>
      </Resource>
    </Request>
    <Sequence>8</Sequence>
  </OrderedRequest>
</ArrayOfOrderedRequest>'


 DECLARE @loops INT

-- Total count of <ID> Nodes -- in this case calling the variable loops
SELECT RPL.ResourceXML.value('declare namespace ns="http://schemas.datacontract.org/2004/07/NewWorld.Aegis.Cad.Common.Broker.Contract.ResponsePlans";
 count(/ns:ArrayOfOrderedRequest/ns:OrderedRequest/ns:Request/ns:Resource/ns:ID)', 'int')  as loops
from   
NwsAegisCAD.Response.ResponsePlan as RPL 
where  RPL.ResponsePlanID =226;

DECLARE @i INT
-- Set counter variable to 1
SET @i = 1 

-- loop starts
WHILE  @i <=  @loops  
BEGIN

 -- variable to store UNIT ID
DECLARE @UnitID  INT

--select unitid to the variable

Select
   @UnitID= @x.value('ID[1]', 'INT')   
FROM @x.nodes('/ArrayOfOrderedRequest/OrderedRequest/Request/Resource/ID[position()=sql:variable("@i")]')
e(x)

-- increment counter    
SET @i = @i + 1   

PRINT @UnitID

END

Если я хочу определенный узел или значения, включенные в их теги xml, этот запрос работает Я былдико не удалось получить параметр @i, переданный в запрос xml.value

Select RPL.Name as PlanName,  

RPL.ResourceXML.value('declare namespace ns="http://schemas.datacontract.org/2004/07/NewWorld.Aegis.Cad.Common.Broker.Contract.ResponsePlans";
 count(/ns:ArrayOfOrderedRequest/ns:OrderedRequest/ns:Request/ns:Resource/ns:ID)', 'int') as COUNT_unitIDs,

RPL.ResourceXML.query('declare namespace ns=
"http://schemas.datacontract.org/2004/07/NewWorld.Aegis.Cad.Common.Broker.Contract.ResponsePlans"; 
for $unitID in 
/ns:ArrayOfOrderedRequest/ns:OrderedRequest/ns:Request/ns:Resource/ns:ID  order by $unitID descending return $unitID') as all_the_RPlan_unitIDs ,

RPL.ResourceXML.value('declare namespace ns="http://schemas.datacontract.org/2004/07/NewWorld.Aegis.Cad.Common.Broker.Contract.ResponsePlans";
(/ns:ArrayOfOrderedRequest/ns:OrderedRequest/ns:Request/ns:Resource/ns:ID)[1]', 'int') as first_UnitID

from   
NwsAegisCAD.Response.ResponsePlan as RPL 
where  RPL.ResponsePlanID =226;

............................................. ..............................................

Я прочитал и перечитываю эти ранее опубликованные запросы и обе статьи MS.

Как выполнить итерацию по узлам поля XML в T-SQL?

sql server xml.value скелет динамические кейсы

Передать Count (*) в переменную через T-SQL

XQUERY - Как использовать sql: variable в функции 'value ()'?

https://docs.microsoft.com/en-us/sql/t-sql/xml/value-method-xml-data-type?view=sql-server-2017

https://docs.microsoft.com/en-us/sql/xquery/xquery-extension-functions-sql-variable?view=sql-server-2017

Благодарим Вас за потраченное время и любые советы, которые вы могли бы рассказать о том, как решить эту проблему.

1 Ответ

0 голосов
/ 26 апреля 2018

Для вашего следующего вопроса: Пожалуйста, уменьшите пример данных до необходимого минимума. Если больше 1, достаточно 2 ...

Вы не указали ожидаемый результат, но следующее вернет каждый и все . Мне пришлось сделать некоторые предположения относительно данных, относящихся к 1: n и 1: 1. Так что для этого могут потребоваться некоторые модификации.

Нет необходимости в петле (избегайте петель, если это возможно!).

Если вы хотите выбрать специальный <Request>, вы можете поместить предикат в .nodes():

DECLARE @x XML

SET @x =
N'<ArrayOfOrderedRequest xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/NewWorld.Aegis.Cad.Common.Broker.Contract.ResponsePlans">
    <OrderedRequest>
    <Request i:type="RequestWithResource">
        <BackupList>
        <RequestBackup>
            <Request i:type="RequestWithResource">
            <NodeID>f1e00f33-0451-4b25-b69a-6c5f6e358fa6</NodeID>
            <Quantity>1</Quantity>
            <Action>Dispatch</Action>
            <Resource>
                <ID>160</ID>
                <ResourceType>1</ResourceType>
            </Resource>
            </Request>
            <Sequence>0</Sequence>
        </RequestBackup>
        </BackupList>
        <NodeID>7b901b61-5c7b-4429-a306-d42f7b367e14</NodeID>
        <Quantity>1</Quantity>
        <Action>Dispatch</Action>
        <Resource>
        <ID>3989</ID>
        <ResourceType>2</ResourceType>
        </Resource>
    </Request>
    <Sequence>1</Sequence>
    </OrderedRequest>
    <OrderedRequest>
    <Request i:type="RequestWithResource">
        <BackupList>
        <RequestBackup>
            <Request i:type="RequestWithResource">
            <NodeID>e4eedaf1-3a7e-4bb5-824c-84efebcab2dd</NodeID>
            <Quantity>1</Quantity>
            <Action>Dispatch</Action>
            <Resource>
                <ID>164</ID>
                <ResourceType>1</ResourceType>
            </Resource>
            </Request>
            <Sequence>0</Sequence>
        </RequestBackup>
        </BackupList>
        <NodeID>1df4b869-5ec8-4582-91f6-28c174aa99ed</NodeID>
        <Quantity>1</Quantity>
        <Action>Dispatch</Action>
        <Resource>
        <ID>3988</ID>
        <ResourceType>2</ResourceType>
        </Resource>
    </Request>
    <Sequence>2</Sequence>
    </OrderedRequest>
    <OrderedRequest>
    <Request i:type="RequestWithResource">
        <NodeID>f30cd65e-5919-44a5-9977-6e04db9a738b</NodeID>
        <Quantity>1</Quantity>
        <Action>Dispatch</Action>
        <Resource>
        <ID>3991</ID>
        <ResourceType>2</ResourceType>
        </Resource>
    </Request>
    <Sequence>3</Sequence>
    </OrderedRequest>
    <OrderedRequest>
    <Request i:type="RequestWithResource">
        <BackupList>
        <RequestBackup>
            <Request i:type="RequestWithResource">
            <NodeID>1df52ab3-ea2f-45e8-af34-f651625cd1ca</NodeID>
            <Quantity>1</Quantity>
            <Action>Dispatch</Action>
            <Resource>
                <ID>124</ID>
                <ResourceType>1</ResourceType>
            </Resource>
            </Request>
            <Sequence>0</Sequence>
        </RequestBackup>
        </BackupList>
        <NodeID>4d1224ee-998d-48e9-8c9c-a74762d0c944</NodeID>
        <Quantity>1</Quantity>
        <Action>Dispatch</Action>
        <Resource>
        <ID>3994</ID>
        <ResourceType>2</ResourceType>
        </Resource>
    </Request>
    <Sequence>4</Sequence>
    </OrderedRequest>
    <OrderedRequest>
    <Request i:type="RequestWithResource">
        <BackupList>
        <RequestBackup>
            <Request i:type="RequestWithResource">
            <NodeID>fee1da03-f490-423d-bdcc-aa7195d560a0</NodeID>
            <Quantity>1</Quantity>
            <Action>Dispatch</Action>
            <Resource>
                <ID>160</ID>
                <ResourceType>1</ResourceType>
            </Resource>
            </Request>
            <Sequence>0</Sequence>
        </RequestBackup>
        </BackupList>
        <NodeID>6c4209fe-9d8c-48fd-8f9f-6a38299ac368</NodeID>
        <Quantity>1</Quantity>
        <Action>Dispatch</Action>
        <Resource>
        <ID>4846</ID>
        <ResourceType>2</ResourceType>
        </Resource>
    </Request>
    <Sequence>5</Sequence>
    </OrderedRequest>
    <OrderedRequest>
    <Request i:type="RequestWithResource">
        <BackupList>
        <RequestBackup>
            <Request i:type="RequestWithResource">
            <NodeID>41ccb2b1-0e6c-4a54-b1bd-ab22152cdd6b</NodeID>
            <Quantity>1</Quantity>
            <Action>Dispatch</Action>
            <Resource>
                <ID>164</ID>
                <ResourceType>1</ResourceType>
            </Resource>
            </Request>
            <Sequence>0</Sequence>
        </RequestBackup>
        </BackupList>
        <NodeID>218da0c7-fdd1-4e20-a62b-feba25a28095</NodeID>
        <Quantity>1</Quantity>
        <Action>Dispatch</Action>
        <Resource>
        <ID>4844</ID>
        <ResourceType>2</ResourceType>
        </Resource>
    </Request>
    <Sequence>6</Sequence>
    </OrderedRequest>
    <OrderedRequest>
    <Request i:type="RequestWithResource">
        <BackupList>
        <RequestBackup>
            <Request i:type="RequestWithResource">
            <NodeID>f86419eb-177f-4e3f-bdc2-6d8fd1e3f123</NodeID>
            <Quantity>1</Quantity>
            <Action>Dispatch</Action>
            <Resource>
                <ID>160</ID>
                <ResourceType>1</ResourceType>
            </Resource>
            </Request>
            <Sequence>0</Sequence>
        </RequestBackup>
        </BackupList>
        <NodeID>d588e812-1607-49a7-b1af-20c3c998a8a6</NodeID>
        <Quantity>1</Quantity>
        <Action>Dispatch</Action>
        <Resource>
        <ID>4538</ID>
        <ResourceType>2</ResourceType>
        </Resource>
    </Request>
    <Sequence>7</Sequence>
    </OrderedRequest>
    <OrderedRequest>
    <Request i:type="RequestWithResource">
        <BackupList>
        <RequestBackup>
            <Request i:type="RequestWithResource">
            <NodeID>dd71e9bb-4d92-47a1-b325-e2e0ed6b7405</NodeID>
            <Quantity>1</Quantity>
            <Action>Dispatch</Action>
            <Resource>
                <ID>164</ID>
                <ResourceType>1</ResourceType>
            </Resource>
            </Request>
            <Sequence>0</Sequence>
        </RequestBackup>
        </BackupList>
        <NodeID>3e125708-28ba-4629-b096-d565030cb5c2</NodeID>
        <Quantity>1</Quantity>
        <Action>Dispatch</Action>
        <Resource>
        <ID>4277</ID>
        <ResourceType>2</ResourceType>
        </Resource>
    </Request>
    <Sequence>8</Sequence>
    </OrderedRequest>
</ArrayOfOrderedRequest>';

- Запрос объявляет пространства имен впереди ...

WITH XMLNAMESPACES(DEFAULT 'http://schemas.datacontract.org/2004/07/NewWorld.Aegis.Cad.Common.Broker.Contract.ResponsePlans'
                            ,'http://www.w3.org/2001/XMLSchema-instance' AS i)
SELECT oRq.value(N'(Request/@i:type)[1]',N'nvarchar(max)') AS Request_Type
        ,oRq.value(N'(Request/NodeID/text())[1]',N'uniqueidentifier') AS Request_ID
        ,oRq.value(N'(Request/Quantity/text())[1]',N'int') AS Request_Quantity
        ,oRq.value(N'(Request/Action/text())[1]',N'nvarchar(max)') AS Request_Action

        --Seems to be 1:1, therefore no .nodes() but just a longer XPath
        ,oRq.value(N'(Request/Resource/ID/text())[1]',N'int') AS Request_Resource_ID
        ,oRq.value(N'(Request/Resource/ResourceType/text())[1]',N'int') AS Request_Resource_ResourceType

        --Sequence is living on the same level as <Request>
        ,oRq.value(N'(Sequence/text())[1]',N'int') AS Request_Sequence

        --Seems to be 1:1 too, the usage of .nodes() is for better readability, a longer XPath was okay as well
        ,rBkp.value(N'(Request/@i:type)[1]',N'nvarchar(max)') AS Backup_Request_Type
        ,rBkp.value(N'(Request/NodeID/text())[1]',N'uniqueidentifier') AS Backup_Request_ID
        ,rBkp.value(N'(Request/Quantity/text())[1]',N'int') AS Backup_Request_Quantity
        ,rBkp.value(N'(Request/Action/text())[1]',N'nvarchar(max)') AS Backup_Request_Action
FROM @x.nodes(N'/ArrayOfOrderedRequest/OrderedRequest') AS A(oRq)       --All OrderRequests
OUTER APPLY oRq.nodes(N'Request/BackupList/RequestBackup') AS B(rBkp);  --a BackupList (if it exists)
...