如何从SQL Server中的XML中提取关系数据

时间:2009-08-12 16:22:19

标签: sql-server xml sql-server-2005

我是XML世界的新手。我在SQL Server 2005中遇到XML数据类型的问题。 我有一个需要XML参数的存储过程。下面给出的参数值......

DECLARE @productIds xml

SET @productIds =
    '<ROOT>
       <AGENTLIST>
         <AGENT>
           <HOSTAPPLICATIONRECORDKEY>GRI</HOSTAPPLICATIONRECORDKEY>
           <BROKERID>02h21a0539</BROKERID>
           <BROKERSHARE>25</BROKERSHARE>
           <BROKERSTATE>AK</BROKERSTATE>
           <CARRIERCODE>GRIC</CARRIERCODE>
           <PLANCODE>EP02</PLANCODE>
           <COVERAGECODES>
               <COVERAGECODE>TL50IM06</COVERAGECODE>
               <COVERAGECODE>TL50IM10</COVERAGECODE>
           </COVERAGECODES>
           <SPLITBROKERID1>2</SPLITBROKERID1>
           <SPLITBROKERSHARE1>25</SPLITBROKERSHARE1>
           <SPLITBROKERID2></SPLITBROKERID2>
           <SPLITBROKERSHARE2>25</SPLITBROKERSHARE2>
           <SPLITBROKERID3></SPLITBROKERID3>
           <SPLITBROKERSHARE3>25</SPLITBROKERSHARE3>
           <APPSIGNEDDATE>7/31/2009</APPSIGNEDDATE>
         </AGENT>
         <AGENT>
           <HOSTAPPLICATIONRECORDKEY>GRI</HOSTAPPLICATIONRECORDKEY>
           <BROKERID>02h21a0538</BROKERID>
           <BROKERSHARE>25</BROKERSHARE>
           <BROKERSTATE>AK</BROKERSTATE>
           <CARRIERCODE>GRIC</CARRIERCODE>
           <PLANCODE>EP02</PLANCODE>
           <COVERAGECODES>
               <COVERAGECODE>TL50IM07</COVERAGECODE>
               <COVERAGECODE>TL50IM11</COVERAGECODE>
           </COVERAGECODES>
           <SPLITBROKERID1>2</SPLITBROKERID1>
           <SPLITBROKERSHARE1>25</SPLITBROKERSHARE1>
           <SPLITBROKERID2></SPLITBROKERID2>
           <SPLITBROKERSHARE2>25</SPLITBROKERSHARE2>
           <SPLITBROKERID3></SPLITBROKERID3>
           <SPLITBROKERSHARE3>25</SPLITBROKERSHARE3>
           <APPSIGNEDDATE>7/31/2009</APPSIGNEDDATE>
         </AGENT>
       </AGENTLIST>
     </ROOT>'

我的存储过程应该为每个Broker返回所有Broker ID及其相应的Coverage Code ...

任何帮助都将受到高度赞赏

1 个答案:

答案 0 :(得分:1)

这对你有什么用?

SELECT 
    PID.NDS.value('(BROKERID)[1]', 'varchar(50)') AS 'BrokerID',
    CCS.CC.value('(.)[1]', 'varchar(50)') AS 'CoverageID'
FROM
    @productIds.nodes('/ROOT/AGENTLIST/AGENT') AS PID(NDS)
CROSS APPLY
    PID.NDS.nodes('COVERAGECODES/COVERAGECODE') AS CCS(CC)

我得到的结果是:

BrokerID    CoverageID
02h21a0539  TL50IM06
02h21a0539  TL50IM10
02h21a0538  TL50IM07
02h21a0538  TL50IM11

这就是你要找的东西吗?

在Alex Homer撰写的这篇文章“SQL Server 2005 XQuery and XML-DML”中可以找到SQL Server 2005及更高版本中这种XML“技巧”的最佳介绍。

马克