DECLARE @hDoc int
EXEC sp_xml_preparedocument @hDoc output,
'
<HiringManagers>
<HiringManagerName>Lauren</HiringManagerName>
<EmployeeId />
<Email>Lauren@hello.com</Email>
<HiringManagerName>Michael </HiringManagerName>
<EmployeeId />
<Email>Michael@bye.com</Email>
</HiringManagers>
'
SELECT * FROM OPENXML(@hdoc, '/HiringManagers')
WITH (Email varchar(30) 'Email',
HiringManagerName varchar(50) 'HiringManagerName')
EXEC sp_xml_removedocument @hDoc
如何获得Lauren和她的电子邮件,我将如何获得Lauren和Michael的电子邮件和姓名?
答案 0 :(得分:0)
由于SQL Server不支持following-sibling
XPath轴,因此以下是一种解决方法。它首先在HiringManagerName
和Email
派生表中将XML与XML中的出现索引一起粉碎。然后这两个链接在索引上。
DECLARE @xml XML = '
<HiringManagers>
<HiringManagerName>Lauren</HiringManagerName>
<EmployeeId />
<Email>Lauren@hello.com</Email>
<HiringManagerName>Michael </HiringManagerName>
<EmployeeId />
<Email>Michael@bye.com</Email>
</HiringManagers>
';
;WITH ct_mn AS (
SELECT
HiringManagerName=n.v.value('(.)','NVARCHAR(256)'),
rn_index=n.v.value('for $i in . return count(../HiringManagerName[. << $i]) + 1', 'INT')
FROM
@xml.nodes('HiringManagers/HiringManagerName') AS n(v)
),
ct_me AS (
SELECT
Email=n.v.value('(.)','NVARCHAR(256)'),
rn_index=n.v.value('for $i in . return count(../HiringManagerName[. << $i])', 'INT')
FROM
@xml.nodes('HiringManagers/Email') AS n(v)
)
SELECT
ct_mn.HiringManagerName,
ct_me.Email
FROM
ct_mn
INNER JOIN ct_me ON
ct_me.rn_index=ct_mn.rn_index;
结果:
╔═══════════════════╦══════════════════╗
║ HiringManagerName ║ Email ║
╠═══════════════════╬══════════════════╣
║ Lauren ║ Lauren@hello.com ║
║ Michael ║ Michael@bye.com ║
╚═══════════════════╩══════════════════╝