0

我正在使用 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 )

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

最后,我希望看到这样的表格:

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

1 回答 1

2

Your XML uses a namespace, so you need the WITH XMLNAMESPACES clause:

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 );
于 2012-09-06T01:59:00.140 回答