下面是输出第一个查询中的原始详细信息和第二个查询中的不同值的示例代码。第一个查询将帮助您验证第二个查询的结果。以下是此解决方案的 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);