sql从XML参数中选择数据

时间:2010-11-19 17:11:50

标签: sql xml sql-server-2005

SQL是如何从这个XML块中选择值的,如下面的示例所示?

<RWFCriteria reportType="OPRAProject">
   <item id="88" name="" value="" type="Project" />
   <item id="112" name="" value="12" type="Milestone" />
   <item id="43" name="" value="11" type="Milestone" />
</RWFCriteria>

我想选择类似于此但使用上述XML数据

DECLARE @Param XML  
SET @Param = '<data>  
      <release id="1"><milestone id="1" /><milestone id="2" /></release>  
      <release id="3"><milestone id="1" /><milestone id="27"/></release>  
    </data>'  

SELECT c.value('../@id', 'INT') AS ReleaseId, c.value('@id', 'INT') AS MilestoneId  
 FROM @Param.nodes('/data/release/milestone') AS T(c)

我只想要节点中的数据,其中type =“Milestone”

1 个答案:

答案 0 :(得分:3)

这样的事情:

DECLARE @Param XML  
SET @Param = '<RWFCriteria reportType="OPRAProject">
                 <item id="88" name="" value="" type="Project" />
                 <item id="112" name="" value="12" type="Milestone" />
                 <item id="43" name="" value="11" type="Milestone" />
               </RWFCriteria>'  


SELECT 
     RWF.item.value('@id', 'INT') AS 'Id', 
     RWF.item.value('@name', 'VARCHAR(100)') AS 'Name',
     RWF.item.value('@value', 'INT') AS 'Value', 
     RWF.item.value('@type', 'VARCHAR(100)') AS 'Type'
FROM 
     @Param.nodes('/RWFCriteria/item') AS RWF(item)
WHERE
     RWF.item.value('@type', 'VARCHAR(100)') = 'Milestone'

结果输出:

Id  Name    Value   Type
112           12    Milestone
 43           11    Milestone