April 25, 2006 at 11:12 am
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
Amit Lohia
April 26, 2006 at 8:23 am
Where are you exectuting this code?
What application?
April 26, 2006 at 9:12 am
SQL 2005
Amit Lohia
April 26, 2006 at 9:43 am
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]
Jack Corbett
Consultant - Straight Path Solutions
Check out these links on how to get faster and more accurate answers:
Forum Etiquette: How to post data/code on a forum to get the best help
Need an Answer? Actually, No ... You Need a Question
April 26, 2006 at 9:46 am
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".
Amit Lohia
April 26, 2006 at 11:07 am
Here is the correct answer
('(/Test[1]/@GUID)','int')
Amit Lohia
May 16, 2006 at 6:06 pm
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
May 17, 2006 at 10:35 am
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
May 22, 2006 at 2:23 pm
Viewing 9 posts - 1 through 8 (of 8 total)
You must be logged in to reply to this topic. Login to reply