Please check below query.
declare @xmlRoot as xml
set @xmlRoot= '<Root>
<table1 col1="2012-03-02T16:42:55.777">
<table2Array>
<Table2 col2="abc">
</Table2>
<Table2 col2="def">
</Table2>
</table2Array>
</table1>
<table1 col1="2012-03-02T17:42:55.777">
<table2Array>
<Table2 col2="abc1">
</Table2>
<Table2 col2="def1">
</Table2>
</table2Array>
</table1>
</Root>'
declare @a as varchar(1)
set @a= '1'
SELECT
col1 = item.value('./@col2', 'varchar(10)')
FROM @xmlRoot.nodes('Root/table1[1]/table2Array/Table2' ) AS T(item);
–The above query return expected output
SELECT
col1 = item.value('./@col2', 'varchar(10)')
FROM @xmlRoot.nodes('Root/table1[*[local-name()=sql:variable("@a")]]/table2Array/Table2' )
AS T(item);
–The above query doesn’t return expected output
what am I doing wrong here?
Since I dont have a key value in parent node to identify child node. I have to parse through index.
This worked for me: