





Have you ever got this error message when you tried to parse an XML string in SQL Server?
XQuery [value()]: ‘value()’ requires a singleton (or empty sequence), found operand of type ‘xdt:untypedAtomic *’
DECLARE @XMLToParse XML -- Load the XML data in to a variable to work with. -- This would typically be passed as a parameter to a stored proc SET @XMLToParse = '' SELECT @XMLToParse.value('data(/Animal/AnimalName)', 'VARCHAR(MAX)') AS AnimalName Baboon
How do we fix this?
This error is saying that the value() function needs an xpath that only exits once (non-repeating node). You and I know that there will only be one instance of
DECLARE @XMLToParse XML -- Load the XML data in to a variable to work with. -- This would typically be passed as a parameter to a stored proc SET @XMLToParse = '' SELECT @XMLToParse.value('data(/Animal/AnimalName)[1]', 'VARCHAR(MAX)') AS AnimalName -- Notice the [1] on the line above! Baboon
Extra Fun
If there are multiple nodes with the same name in your XML, you can adjust the number inside the square braces to match whatever node you want. For example:
Baboon Cat Dog
[1] would return Baboon
[2] would return Cat
[3] would return Dog