Consider the following xml:
<Persons num="3">
<Person age="5" />
<Person age="19" />
</Persons>
You need to extract this xml into a relational table:
Persons table (Age1 int, Age2 int, Age3 int , Age4 int)
The analysis must satisfy the following restrictions:
- all persons with an age> = 18 should be assigned to the columns with the lowest column number, and the value should be 18
- If a personโs age is not specified, it is 18.
- all persons with age <18 must follow
- if the number of participants is less than 4, those that are not indicated must be of age = -1
In this example, there are 3 people, of which 2 of them: 5 and 19, respectively. Table of Contents Persons should be as follows:
18 18 5 -1
Is there a better way to do this using xpath?
So far, I can parse the xml and assign an age, but it's not clear how to do the ordering:
declare @XmlData xml =
'<Persons num="3">
<Person age="5" />
<Person age="19" />
</Persons>'
declare @Persons table (Age1 int, Age2 int, Age3 int , Age4 int)
insert into @Persons (Age1, Age2, Age3, Age4)
select ISNULL(Age1, case when Num>= 1 then 18 else -1 end) Age1
, ISNULL(Age2, case when Num>= 2 then 18 else -1 end) Age2
, ISNULL(Age3, case when Num>= 3 then 18 else -1 end) Age3
, ISNULL(Age4, case when Num>= 4 then 18 else -1 end) Age4
from (
select Persons.Person.value('@num','smallint') as Num
,Persons.Person.value('Person[@age<18][1]/@age','smallint') as Age1
,Persons.Person.value('Person[@age<18][2]/@age','smallint') as Age2
,Persons.Person.value('Person[@age<18][3]/@age','smallint') as Age3
,Persons.Person.value('Person[@age<18][4]/@age','smallint') as Age4
from @XmlData.nodes('/Persons') Persons(Person)
) Persons
select *
from @Persons
Result
5 18 18 -1