Simple XML

  • DECLARE

    @XML XML

    SET

    @XML = '<Test GUID="6" />'

    SELECT

    @XML.value('(/Test[@GUID])[1]','int')

    SELECT

    @XML.query('/Test[@GUID][1]')

     

    Why SELECT @XML.value('(/Test[@GUID])[1]','int') returns 0 instead of 6

     


    Kindest Regards,

    Amit Lohia

  • Where are you exectuting this code?

    What application?

  • SQL 2005


    Kindest Regards,

    Amit Lohia

  • I believe you want:

    SELECT @XML.value('(/[@GUID])[1]','int')

    SELECT

    @XML.query('/[@GUID][1]')

    as you are already at the root and the /Test is trying to find a value in Test/Test[@GUID]

  • I have tried that , but is gives an syntax error

    Msg 2256, Level 16, State 1, Line 5

    XQuery [value()]: Syntax error near '[', expected a "node test".

     


    Kindest Regards,

    Amit Lohia

  • Here is the correct answer

    ('(/Test[1]/@GUID)','int')


    Kindest Regards,

    Amit Lohia

  • No, that's not the correct answer. That's an answer that works, but it's not correct.

    The correct answer is

    /Test/@GUID

    There's no need to specify the "[1]" predicate, because the pattern "/Test" will always match exactly one node: the "Test" element that's the root element of the document.

    The "[1]" won't harm anything, but the Pragmatics would call that "programming by coincidence," and they'd be right.

    Robert Rossney

    rbr@well.com

  • Robert:  the [1] is required, the Pragmatics would call it RTFM.

    The xquery.value() function requires a singleton result.  Even though, in this case, leaving out the [1] will return a singleton (it's well-formed XML and you're looking at the root element), the expression is evaluated before the node test is performed. 

    XML Variables may hold document fragments as weel as well-formed documents with root elements. (Try using SET @XML = '<a/><Test GUID="6" /><Test GUID="7" /><Test GUID="8" />' )

    The parser requires the [1] so you are explicitly stating there will be a single result.

    -Eddie

    Eddie Wuerch
    MCM: SQL

  • Oh, good heavens, XQuery. Never mind then; you're quite right.

    Robert Rossney

    rbr@well.com

Viewing 9 posts - 1 through 8 (of 8 total)

You must be logged in to reply to this topic. Login to reply