将包含XML的VARCHAR列转换为表

时间:2012-09-06 01:33:50

标签: sql sql-server sql-server-2008

我正在使用VMware vCenter 5,并希望创建已创建的DRS规则的快速报告。以下是数据的摘录:

<obj xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:vim25" versionId="5.0" xsi:type="ArrayOfClusterRuleInfo">
  <ClusterRuleInfo xsi:type="ClusterAffinityRuleSpec">
    <key>1</key>
    <enabled>true</enabled>
    <name>SQL Servers</name>
    <vm type="VirtualMachine" xsi:type="ManagedObjectReference">vm-100</vm>
    <vm type="VirtualMachine" xsi:type="ManagedObjectReference">vm-200</vm>
    <vm type="VirtualMachine" xsi:type="ManagedObjectReference">vm-300</vm>
  </ClusterRuleInfo>
  <ClusterRuleInfo xsi:type="ClusterAntiAffinityRuleSpec">
    <key>2</key>
    <enabled>true</enabled>
    <name>Oracle DBs</name>
    <vm type="VirtualMachine" xsi:type="ManagedObjectReference">vm-1000</vm>
    <vm type="VirtualMachine" xsi:type="ManagedObjectReference">vm-2000</vm>
  </ClusterRuleInfo>
</obj>

请注意,每个规则的VM数可能会有所不同。

我无法将此XML数据转换为表格,所以我尝试使用此查询找到名称(在标记内):

SELECT ref.value('name[1]', 'varchar(200)') as [enabled]
FROM @data.nodes('/obj/ClusterRuleInfo') data( ref )

它不返回任何数据。我发现,如果我删除和线条,它可以工作,但我不知道为什么。我相信这是因为SQL Server不理解XML模式(或类似的东西 - 我不是XML专家)。

最后,我想看到这样一张桌子:

Name           VM
-----------   ----
SQL Servers    100
SQL Servers    200
SQL Servers    300
Oracle DBs    1000
Oracle DBs    2000

1 个答案:

答案 0 :(得分:2)

您的XML使用命名空间,因此您需要WITH XMLNAMESPACES子句:

declare @data xml;
set @data = '
<obj xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:vim25" versionId="5.0" xsi:type="ArrayOfClusterRuleInfo">
  <ClusterRuleInfo xsi:type="ClusterAffinityRuleSpec">
    <key>1</key>
    <enabled>true</enabled>
    <name>SQL Servers</name>
    <vm type="VirtualMachine" xsi:type="ManagedObjectReference">vm-100</vm>
    <vm type="VirtualMachine" xsi:type="ManagedObjectReference">vm-200</vm>
    <vm type="VirtualMachine" xsi:type="ManagedObjectReference">vm-300</vm>
  </ClusterRuleInfo>
  <ClusterRuleInfo xsi:type="ClusterAntiAffinityRuleSpec">
    <key>2</key>
    <enabled>true</enabled>
    <name>Oracle DBs</name>
    <vm type="VirtualMachine" xsi:type="ManagedObjectReference">vm-1000</vm>
    <vm type="VirtualMachine" xsi:type="ManagedObjectReference">vm-2000</vm>
  </ClusterRuleInfo>
</obj>';

WITH XMLNAMESPACES('urn:vim25' AS ns)
SELECT 
  ref.value('../ns:name[1]','nvarchar(256)') AS Name, 
  STUFF(ref.value('.','nvarchar(256)'),1,3,'') AS VM
FROM @data.nodes('/ns:obj/ns:ClusterRuleInfo/ns:vm') data( ref );