Juvil
Juvil

Reputation: 490

how to do XQuery - tsql

I got this XML.

<ArrayOfGuid xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
     <guid>475B07C8-CDEA-4000-BAAE-485336190E10</guid>
     <guid>6E5B87BC-CF80-4AB2-939E-ED951FA604AB</guid>
     <guid>31BFDA60-3BB2-49DC-8C69-10F6E1B540CA</guid>
</ArrayOfGuid>

Need to get the results like

BatchGUID
475B07C8-CDEA-4000-BAAE-485336190E10
6E5B87BC-CF80-4AB2-939E-ED951FA604AB
31BFDA60-3BB2-49DC-8C69-10F6E1B540CA

Somehow I am stuck with

DECLARE @BatchGUID XML

SET @BatchGUID = '<ArrayOfGuid xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
                      <guid>475B07C8-CDEA-4000-BAAE-485336190E10</guid>
                      <guid>6E5B87BC-CF80-4AB2-939E-ED951FA604AB</guid>
                      <guid>31BFDA60-3BB2-49DC-8C69-10F6E1B540CA</guid>
                    </ArrayOfGuid>'

DECLARE @t_xml TABLE
(
    BatchGUID XML
)

INSERT INTO @t_xml
SELECT @BatchGUID

SELECT C.* FROM @t_xml
cross apply (select name.value('guid[1]', 'uniqueidentifier') as [BatchGUID] 
from BatchGUID.nodes('//ArrayOfGuid/guid') as c(name)) as C

This is returning me

BatchGUID
NULL
NULL
NULL

Need to know what I'm doing wrong here.

Thanks,

Upvotes: 2

Views: 570

Answers (1)

Kirk Broadhurst
Kirk Broadhurst

Reputation: 28728

You are so very close!

Your problem is that you're selecting the value of the guid[1] node from within the guid node. Of course, the guid node doesn't contain any children - you want to select the value from that node itself (which is expressed as .)

SELECT C.* FROM @t_xml
cross apply (select name.value('.', 'uniqueidentifier') as [BatchGUID]
from @BatchGUID.nodes('//ArrayOfGuid/guid') as c(name)) as C

Upvotes: 1

Related Questions