I have a table variable with the folling columns:
[ID] TINYINT
[XML] XML
The XML structure looks like:
<conditions>
<condition type='expresion'>
...
</condition>
<condition type='operand'>
...
</condition>
<condition type='expresion'>
...
</condition>
<condition type='operand'>
...
</condition>
<condition type='expresion'>
...
</condition>
</conditions>
I need to extract the information above and populate a table with the following sturcuture:
[ID]
[ConditionID]
[ConditionXML]
where ConditionID will be numeric column and ConditonXML will be extrated from the original XML.
What is very important to me is to generate ConditionID values in way to represent the order in the original XML structure.
I have read that this could be done using ROW_NUMBER like this:
SELECT [ID]
,ROW_NUMBER() OVER (PARTITION BY [ID] ORDER BY T.c) AS T
,T.c.query('.')
FROM @Test
CROSS APPLY [CondtionsXML].nodes('conditions/condition') T(c)
ORDER BY [ID], T
but in the official documentation is said, that:
There is no guarantee that the rows returned by a query using ROW_NUMBER() will be ordered exactly the same with each execution unless the following conditions are true:
- Values of the partitioned column are unique.
- Values of the ORDER BY columns are unique.
- Combinations of values of the partition column and ORDER BY columns are unique.
and since my operand nodes can be the same I am worried I may have some issues. Also, if I remove the PARTITON BY clause, the things goes wrong.
Other tenique I could use is to create a separete tale with INDENTITY column and insert values into it like this:
DECLARE @TEST1 TABLE
(
[ID] SMALLINT IDENTITY(1,1)
,[ParentID] TINYINT
,[XML] XML
)
INSERT INTO @TEST1 ([ParentID], [XML])
SELECT [ID]
,T.c.query('.')
FROM @Test
CROSS APPLY [CondtionsXML].nodes('conditions/condition') T(c)
Could anyone say if this is the way to insert XML nodes in a table in the order they are represented in the XML structurer.