Given a XML structured like this:
<ROOT_NODE>
<FOLDER_LIST>
<FOLDER>
<CODE_FOLDER>1</CODE_FOLDER>
<DESCRIPTION>This is a folder</DESCRIPTION>
<DATA_LIST>
<DATA>
<CODE_DATA>100</CODE_DATA>
<OPTIONS>
<OPTION>
<CODE_OPTION>200</CODE_OPTION>
<PRINT_TEXT>This is a test</PRINT_TEXT>
</OPTION>
<OPTION>
<CODE_OPTION>200</CODE_OPTION>
<PRINT_TEXT>This is a test</PRINT_TEXT>
</OPTION>
</OPTIONS>
</DATA>
</DATA_LIST>
</FOLDER>
</FOLDER_LIST>
</ROOT_NODE>
First I put the values of the first level (FOLDER) inside a temporary table called @tmpFolders using
FROM @xml.nodes('ROOT_NODE/FOLDER_LIST/FOLDER') as folder(id)
Then I declared a cursor on @tmpFolders
DECLARE cur CURSOR FOR
SELECT CODE_FOLDER, DESCRIPTION FROM @tmpFolders
OPEN cur
FETCH NEXT FROM cur INTO @codeFolder, @description
WHILE (@@FETCH_STATUS = 0)
Inside the cursor I insert the values of the second level (DATA) using CROSS APPLY into another temporary table called @tmpData
INSERT INTO @tmpData(CODE_DATA)
SELECT data.id.value('CODE_DATA[1]','INT'))
FROM @xml.nodes('ROOT_NODE/FOLDER_LIST/FOLDER') as folder(Id)
CROSS APPLY folder.Id.nodes('DATA_LIST/DATA') as data(Id)
Up to this point, everything works correctly. Now I need the get the values from the third level (OPTION) and insert them into another temporary table called @tmpOptions I tried adding another CROSS APPLY but without success
INSERT INTO @tmpOptions(CODE_OPTION, PRINT_TEXT)
SELECT data.id.value('CODE_DATA[1]','INT')),
option.id.value('CODE_OPTION[1]','INT'))
option.id.value('PRINT_TEXT[1]','VARCHAR(50)'))
FROM @xml.nodes('ROOT_NODE/FOLDER_LIST/FOLDER') as folder(Id)
CROSS APPLY folder.Id.nodes('DATA_LIST/DATA') as data(Id)
CROSS APPLY data.Id.nodes('OPTIONS/OPTION') as option(Id)
I don't get any errors, so I'm not sure what I'm doing wrong.