简体   繁体   中英

SQL Server 2008 & XQUERY

I'm currently using Xquery in SQL Server to extract some information from XML.

I'm having troubles because I have to put some dynamics content on one variable but it doesn't work.

When I select this :

P.value('ListOrderItem[1]/OrderItem[1]/Item[sql:variable("@I")]/Seller[1]','VARCHAR(64)')

P is my path and it's good because it's working with other items, but I have to do a loop on this item (in one order, you can have many items...), so that's why I want to put the @I and then do a loop on this variable.

PS: Don't say to put the [1] after the variable, else it will select the first item every time.

Edit: By "doesn't work" i mean that it send me only the first item when i put the [1] and error message when i put " [sql:variable("@I")] " which is "value()' requires a singleton (or empty sequence), found operand of type 'xdt:untypedAtomic *"

And of course, i've tried the '+@I' but it still doesn't work..

Example of my XML :

<ListOrderItem>
 <OrderItem>
  <Item>
   ...
  </Item>
  <Item>
   ...
  </Item>
 </OrderItem>
</ListOrderItem>

Final edit : I finally fixed the problem this post helped me a lot, sorry for posting then.

Getting multiple records from xml column with value() in SQL Server

Thanks.

Try this...

select v.x.value('.','varchar(20)')
from
   p.nodes('ListOrderItem/OrderItem//Seller[1]') v(x)

Embed your entire expression in parenthesis and add the [1] to the end.

declare @XML xml = '
<ListOrderItem>
 <OrderItem>
  <Item>
   <Seller>1</Seller>
  </Item>
  <Item>
   <Seller>2</Seller>
  </Item>
 </OrderItem>
</ListOrderItem>'


declare @I int = 2

select @XML.value('(ListOrderItem[1]/OrderItem[1]/Item[sql:variable("@I")]/Seller[1])[1]','VARCHAR(64)')

Result: 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM