[英]SQL Server - XQuery - Substring
What is the best way to retrieve values A and B on SQL Server? 在SQL Server上检索值A和B的最佳方法是什么? I have the following as a part of an XML type column.
我有以下作为XML类型列的一部分。
<Data Name=""Teams"">
<Data DataElement=""Test"" Value=""FirstTeam=A;SecondTeam=B;""/>
</Data>
Is it better to substring the query result (ie use sql substring) or is it more efficient to substring the xquery result (ie use substring in the xquery)? 是否更好地对查询结果进行子串(即使用sql substring)或者是否更有效地对xquery结果进行子串(即在xquery中使用子字符串)?
Thank you 谢谢
You can use normal xml.nodes to get that value from xml and then parse the value based on the requirement 您可以使用普通的xml.nodes从xml获取该值,然后根据需求解析该值
declare @xml xml =
'<Data Name="Teams">
<Data DataElement="Test" Value="FirstTeam=A;SecondTeam=B;"/>
</Data>'
select x.r.value(N'@Value', N'varchar(100)') as val from @xml.nodes('Data/Data') as x(r)
What does as a part of an XML type column mean? 作为XML类型列的一部分意味着什么?
"
signs?) "
符号?) Data
within Data
...) Data
中的嵌套Data
......) Is there a reason not to put this like (much better to query!)? 有没有理由不这样(更好的查询!)?
<Teams>
<Team DataElement="Test" Name="A"/>
<Team DataElement="Test" Name="B"/>
</Teams>
As XML has - other than SQL Server - an inherent order by position, you would not need a "first" or "second" team. 由于XML(除了SQL Server)是一种固有的排名顺序,因此您不需要“第一”或“第二”团队。 Well, of courrse you can add an attribute to specify this...
那么,你可以添加一个属性来指定这个...
If this is a snippet of a big XML , you have to consider, that 如果这是一个大型XML的片段,你必须考虑这一点
<
which is pretty fast <
非常快 Value="
?) will lead to unexpected results... Value="
?)会导致意想不到的结果...... XML
... For SUBSTRING
you´d have to do an expensive cast... XML
...对于SUBSTRING
你必须做一个昂贵的演员...... So my clear advise: Use real XML methods to navigate to the given content and separate the content of @Value
extra. 所以我明确建议:使用真正的XML方法导航到给定的内容并分离
@Value
extra的内容。
Try it like this to get the content: 尝试这样来获取内容:
DECLARE @XML XML=
'<Data Name="Teams">
<Data DataElement="Test" Value="FirstTeam=A;SecondTeam=B;"/>
</Data>';
SELECT @XML.value('(//Data[@DataElement="Test"]/@Value)[1]','nvarchar(max)');
DECLARE @tbl TABLE(YourXMLColumn XML);
INSERT INTO @tbl VALUES
(
'<Data Name="Teams">
<Data DataElement="Test" Value="FirstTeam=A;SecondTeam=B;"/>
</Data>'
);
SELECT Team.value('.','nvarchar(max)') AS Team
FROM @tbl AS tbl
CROSS APPLY (SELECT CAST('<x>' + REPLACE(YourXMLColumn.value('(//Data[@DataElement="Test"]/@Value)[1]','nvarchar(max)'),';','</x><x>') + '</x>' AS XML)) AS Splitted(X)
CROSS APPLY X.nodes('x') AS The(Team)
The result 结果
Team
-----------
FirstTeam=A
SecondTeam=B
(You might split this in two column again, but this is something you should solve on your own now :-). (你可能会再将它分成两列,但这是你现在应该自己解决的问题:-)。
The fact that you have to split one value to get entries you'd have to split again, shows clearly, that this is not the best design... 事实上,您必须拆分一个值才能获得必须再次拆分的条目,这清楚地表明,这不是最好的设计......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.