Try something like this:
DECLARE @input XML = '<footballteams> <team manager="Benitez"> <name>Liverpool</name> <ground>Anfield</ground> </team> <team manager="Mourinho"> <name>Chelsea</name> <ground>Stamford Bridge</ground> </team> <team manager="Wenger"> <name>Arsenal</name> <ground>Highbury</ground> </team> </footballteams>' SELECT TeamName = Foot.value('(name)[1]', 'varchar(100)'), Manager = Foot.value('(@manager)', 'varchar(100)'), Ground = Foot.value('(ground)[1]', 'varchar(100)') FROM @input.nodes('/footballteams/team') AS Tbl(Foot)
Basically, calling .nodes()
creates a pseudo-table called Tbl
with one XML column called Foot
that will contain each <team>
XML node as its value.
Then you can select from this pseudo-table and extract individual values ββof XML attributes ( @manager
) and elements ( name
, ground
) from this XML <team>
fragment and convert them to T -SQL data value of the type of your choice.
To insert these values ββinto your table, simply use the INSERT
based on this:
;WITH ShreddedData AS ( SELECT TeamName = Foot.value('(name)[1]', 'varchar(100)'), Manager = Foot.value('(@manager)', 'varchar(100)'), Ground = Foot.value('(ground)[1]', 'varchar(100)') FROM @input.nodes('/footballteams/team') AS Tbl(Foot) ) INSERT INTO dbo.FootballTeams(Name, Manager, Ground) SELECT TeamName, Manager, Ground FROM ShreddedData
source share