这可能不错,我只是不确定如何最好地表达这个问题。
我有Xml Like
<Names>
<Name Language="English">
<Value></Value>
<FirstName />
<MiddleName />
<LastName />
<IsPrimary>True</IsPrimary>
</Name>
</Names>
其中(名称)可以有多个(名称)。我需要得到多个行(我已经完成了)和所有(值)(连接的第一个/中间/最后一个)都是不同的。
基本上我需要确保所有(Value)都是唯一的。我不确定如何在xml中选择distinct。
谢谢你的帮助
答案 0 :(得分:0)
下面是输出第一个查询中的原始详细信息和第二个查询中的不同值的示例代码。第一个查询将帮助您验证第二个查询的结果。以下是link to a SQL Fiddle for this solution。
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);