从sql字符串中提取数据

时间:2018-05-01 11:01:41

标签: tsql

我在列中有以下数据。我想提取显示为542的“匹配详细信息”分数。问题是匹配分数也可能超过3个字符。有人可以帮忙吗?

 MatchingDetails score="542" maxScore="-96" matchRule="abcdef"><rule name="Person_Forename" score="279" /><rule name="Person_Surname" score="263"

2 个答案:

答案 0 :(得分:1)

一种方法是使用charindexpatindexsubstring的组合:

DECLARE @S varchar(100) = 'MatchingDetails score="542" maxScore="-96" matchRule="abcdef">'


SELECT SUBSTRING(@S, 
                 patindex('% score="%', @S) + 8,
                 charindex('"', @S, patindex('% score="%', @S) + 9) - patindex('% score="%', @S) - 8)

结果:

542

答案 1 :(得分:1)

如果您的数据是XML字符串,可能是这样的

示例(更正的xml)

Declare @S varchar(max) = '
<MatchingDetails score="542" maxScore="-96" matchRule="abcdef" >
    <rule name="Person_Forename" score="279"></rule>
    <rule name="Person_Surname" score="263"></rule>
</MatchingDetails>
'

Select convert(xml,@S).value('MatchingDetails[1]/@score','int')

<强>返回

542