1

这可能还不错,我只是不确定如何最好地表达这个问题。

我有 XML 喜欢

<Names>
  <Name Language="English">
    <Value></Value>
    <FirstName />
    <MiddleName />
    <LastName />
    <IsPrimary>True</IsPrimary>
  </Name>
</Names>

其中(Names)可以有很多(Name)。我需要获取多个行(我已经完成)并且所有(值)(即连接的第一个/中间/最后一个)都是不同的。

所以本质上我需要确保所有(值)都是唯一的。我不确定如何在 xml 中选择 distinct。

谢谢您的帮助

4

1 回答 1

0

下面是输出第一个查询中的原始详细信息和第二个查询中的不同值的示例代码。第一个查询将帮助您验证第二个查询的结果。以下是此解决方案的 SQL Fiddle 链接

CREATE TABLE #Temp
    (XmlString XML);

INSERT INTO #Temp (XmlString)
VALUES 
    ('<Names>
      <Name Language="English">
        <Value></Value>
        <FirstName>Hello Goodbye</FirstName>
        <MiddleName />
        <LastName />
        <IsPrimary>True</IsPrimary>
      </Name>
      <Name Language="English">
        <Value></Value>
        <FirstName>Hello</FirstName>
        <MiddleName />
        <LastName>Goodbye</LastName>
        <IsPrimary>True</IsPrimary>
      </Name>
      <Name Language="English">
        <Value></Value>
        <FirstName>Hello</FirstName>
        <MiddleName />
        <LastName>Goodbye</LastName>
        <IsPrimary>True</IsPrimary>
      </Name>
      <Name Language="English">
        <Value></Value>
        <FirstName>Hello</FirstName>
        <MiddleName>There</MiddleName>
        <LastName>Goodbye</LastName>
        <IsPrimary>True</IsPrimary>
      </Name>
      <Name Language="English">
        <Value></Value>
        <FirstName>No</FirstName>
        <MiddleName>You</MiddleName>
        <LastName>Don''t</LastName>
        <IsPrimary>True</IsPrimary>
      </Name>
    </Names>'), 
    ('<Names>
      <Name Language="English">
        <Value></Value>
        <FirstName>Another</FirstName>
        <MiddleName />
        <LastName>Record</LastName>
        <IsPrimary>True</IsPrimary>
      </Name>
      <Name Language="English">
        <Value></Value>
        <FirstName>No</FirstName>
        <MiddleName>You</MiddleName>
        <LastName>Don''t</LastName>
        <IsPrimary>True</IsPrimary>
      </Name>
    </Names>');

SELECT FirstName = NULLIF(SomeNames.value('(FirstName)[1]', 'VARCHAR(MAX)'), '')
    , MiddleName = NULLIF(SomeNames.value('(MiddleName)[1]', 'VARCHAR(MAX)'), '')
    , LastName = NULLIF(SomeNames.value('(LastName)[1]', 'VARCHAR(MAX)'), '')
FROM #Temp src (NOLOCK) 
CROSS APPLY XmlString.nodes('/Names/Name') AS ShreddedXml (SomeNames);

SELECT DISTINCT FirstName = REPLACE(RTRIM(LTRIM(CONCAT(NULLIF(SomeNames.value('(FirstName)[1]', 'VARCHAR(MAX)'), ''), ' ', NULLIF(SomeNames.value('(MiddleName)[1]', 'VARCHAR(MAX)'), ''), ' ', NULLIF(SomeNames.value('(LastName)[1]', 'VARCHAR(MAX)'), '')))), '  ', ' ')
FROM #Temp src (NOLOCK) 
CROSS APPLY XmlString.nodes('/Names/Name') AS ShreddedXml (SomeNames);
于 2013-06-18T19:56:46.130 回答