So I've just started a new job and have inherited some SQL code - which I and the rest of the team do not understand (as it's written by someone who has now left).
The code deals with inserting xml into a table.
The xml will look something like this: @TheRole = "<descriptions><description>test</description><description>abc</description></descriptions>"
The idea is that each description ("test" and "abc" in this example) need to be inserted to a table called PositionsDescriptions that would look something like this:
DescriptionId Description
1 test
2 abc
And this data is related to a job (or position) in a table called Positions_Descriptions, that would look something like this:
PositionId SectionId DescriptionId OrderNumber
1 1 1 1
1 1 2 2
To insert the descriptions into the PositionsDescriptions and Positions_Descriptions tables, we need to check that the description is not already in the PositionsDescriptions (if it's not, then insert it) and then fill the Positions_Descriptions table. The OrderNumber simply gives us the order in which the descriptions appear
The SQL code for doing this is:
DECLARE @TableRole TABLE(RowID int not null primary key identity(1,1), Description nvarchar(MAX), DescriptionId int) DECLARE @RowsToProcess int, @CurrentRow int, @Description nvarchar(MAX), @OrderNumber int, INSERT INTO @TableRole (Description, DescriptionId) declare cur1 cursor local for select P.DescriptionId, N.Description from ( select T.C.value('.', 'nvarchar(max)') as Description from @TheRole.nodes('/descriptions/description') as T(C) ) as N left outer join PositionsDescriptions as P on P.Description = N.Description open cur1 while 1 = 1 begin fetch cur1 into @DescriptionId, @Description if @@fetch_status <> 0 break if @DescriptionId is null begin insert into PositionsDescriptions (Description) select @Description select @DescriptionId = scope_identity() end insert INTO Positions_Descriptions(PositionId, SectionId, DescriptionId, OrderNumber) VALUES (@PositionId, 1, @DescriptionId, @OrderNumber) set @OrderNumber = @OrderNumber + 1 end close cur1 deallocate cur1
The problem is that when you insert something like @TheRole = "<descriptions><description>test</description><description>abc</description></descriptions>"
then the data is put in incorrectly, and put in in alphabetical order. So the OrderNumber is the wrong way round.
I'm convinced it's something to do with the code in the snippet above, but I can't work out what - can anyone help? Or at least point me in the direction of a more elegant solution?!