Xml sql operation time data, there is sometimes needs to obtain the attribute values, the following examples:
DECLARE @x XML
SET @x='
<root>
<部位 ID="59" 名称="头颅">
<检查方法 ID="1" 名称="正位" />
<检查方法 ID="2" 名称="侧位" />
</部位>
</root>'
These are the xml data to obtain the following results:
部位ID 部位名称 检查方法ID 检查方法名称
59 头颅 1 正位
59 头颅 2 侧位
Implementation code:
SELECT T.c.value('(@ID)[1]','varchar(10)') AS 部位ID ,
T.c.value('(@名称)[1]','varchar(10)') AS 部位名称
,T1.o.value('(@ID)[1]','varchar(10)') AS 检查方法ID
,T1.o.value('(@名称)[1]','varchar(10)') AS 检查方法名称
FROM @x.nodes('/root/部位') T(c)
CROSS APPLY c.nodes('检查方法') T1(o)
result: