Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using xml .nodes() functionality to return all instances

I have the following code but it only returns the first instance of the MonthDate and 'Value' values. I have been experimenting with the .nodes() and Cross Apply but can't figure out the syntax, I keep getting the error of;

Invalid object name 'xmlContent.nodes'.

Code:

Declare @ngTest Table(ID int Identity, XmlContent XML)
Insert into @ngTest(XMLContent)(SELECT TOP 1 Cast(Cast(Data as ntext) as XML) FROM [Accounts].[dbo].[GoalChartData]  where goalID = 3661 and typeID = 2)

SELECT Top 1000 ID, 
    [XmlContent].value('(GoalMonteCarloChartResult/MonthlyMedianResults/MonthlyAmount/MonthDate/node())[1]', 'datetime') as MonthDate,
    [XmlContent].value('(GoalMonteCarloChartResult/MonthlyMedianResults/MonthlyAmount/Value/node())[1]','float') as Value
    from @ngTest CROSS APPLY [xmlContent].nodes('/MonthlyMedianResults/MonthlyAmount')

When I remove the CROSS APPLY conditional it returns the first instance of the MonthDate and value, but I want them all.

Thank you

like image 411
Nick G Avatar asked Jun 06 '26 09:06

Nick G


1 Answers

Most likely, you need something like this:

SELECT Top 1000 
    ID, 
    MonthDate = XCol.value('(MonthDate)[1]', 'DATETIME'),
    [Value] = XCol.value('(Value)[1]', 'FLOAT') 
FROM
    @ngTest 
CROSS APPLY 
    [xmlContent].nodes('/MonthlyMedianResults/MonthlyAmount') AS XTbl(XCol)

The .nodes() call creates a "virtual" table (XTbl) with a single XML column (XCol), where each row represents the XML fragment of each <MonthlyAmount> node (and you must include a AS table-alias(column-alias) to your CROSS APPLY section so you can refer to this virtual table in your query).

You need to apply the XQuery .value() to that virtual table to fetch the values from this virtual table or XML fragments.

like image 129
marc_s Avatar answered Jun 08 '26 23:06

marc_s



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!