This SQL only returns the first Activity element. How do I select them all? If I remove the [1] in the query I get an error that "value() requires a singleton".
DECLARE @myDoc xml
SET @myDoc =
'<Root>
<Activities>
<Activity>This is activity one</Activity>
<Activity>This is activity two</Activity>
<Activity>This is activity three</Activity>
</Activities>
</Root>'
SELECT @myDoc.value('(/Root/Activities/Activity)[1]', 'varchar(100)' )
Here is another situation and solution: I was searching for this situation where there are two elements to be selected using one query.
CREATE TABLE #Table1 (ID INT IDENTITY(1,1),XMLDoc XML)
INSERT INTO #Table1 VALUES ('
<bookstore>
<name>Bookstore1</name>
<location>Location1</location>
<book>
<title>Titile1</title>
<price>40</price>
</book>
</bookstore>')
INSERT INTO #Table1 VALUES ('
<bookstore>
<name>Bookstore2</name>
<location>Location2</location>
<book>
<title>Titile2</title>
<price>50</price>
</book>
</bookstore>')
SELECT ID,
T.c.value('title[1]','varchar(50)') AS 'BookTitile',
T.c.value('price[1]','decimal(18,2)') AS 'Price'
FROM #Table1
CROSS APPLY #Table1.XMLDoc.nodes('/bookstore/book') T(c)
DROP TABLE #Table1
You can modify this as required to include XMLNamespaces. Solution originally found at :https://social.msdn.microsoft.com/Forums/sqlserver/en-US/35e75e32-9ffb-4a30-8637-2cc928554763/selecting-multiple-values-from-multiple-rows-of-xml?forum=sqlxml
Thanks Ed, but I found an easier version:
SELECT T.C.value('.', 'varchar(100)') as activity
FROM @myDoc.nodes('(/Root/Activities/Activity)') as T(C)
Though from your "unnecessarily complex" example it seems worryingly simple..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With