尝试这样的事情:
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)
基本上,.nodes()
创建伪“表”的调用Tbl
使用单个 XML 列调用Foot
,该列将包含每个<team>
XML 节点作为其值。
然后,您可以从该伪表中进行选择,并从该XML 片段中提取 XML 属性 ( @manager
) 和元素 ( name
, ) 的各个值,并将它们转换为您选择的类型的 T-SQL 数据值。ground
<team>
要将这些值插入到您的表中 - 只需使用INSERT
基于此的语句:
;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