使用Substring / CharIndex

时间:2019-04-24 09:16:19

标签: sql-server tsql substring

我必须从数据库的“不干净”字段中提取文本。有人知道如何仅提取以下示例中的“每日使用量过高” 吗?

Order: T001.1<br />Rejection Reason: Meter Read Rejected: daily usage too high<br /><br /><a href='http://********?ProfileId=111111&AccountId=22222&ProductId=11111&MeterId=11111'>Link to page</a>

另一个例子:

<b>Order: </b>Notification<br /><b>Rejection Reason: </b>Meter Read Rejected: daily usage too high<br /><br /><br /><a href='http://********ProfileId=11111&AccountId=11111&ContractId=1111&WaterId=2222&MeterId=22222&MOT=true'>Meter page</a>

2 个答案:

答案 0 :(得分:0)

我假设您要查找第三次出现的:<br>之间的值

如果是这样,可以将Stuffcross apply一起使用。这里需要cross apply来找到:的第三次出现

SELECT 
SUBSTRING(STUFF(texi, 1, CHARINDEX(':',texi,P3.pos), ''), 0, 
          CHARINDEX('<', STUFF(texi, 1, CHARINDEX(':',texi,P3.pos), ''))) as mystring
from test
cross apply (select (CHARINDEX(':',texi))) as P1(Pos)
cross apply (select (CHARINDEX(':',texi, P1.Pos+1))) as P2(Pos)
cross apply (select (CHARINDEX(':',texi, P2.Pos+1))) as P3(Pos)

CHECK DEMO HERE

答案 1 :(得分:0)

您可以查找字符串'Meter Read Rejected',然后获取值:

select left(v.str, patindex('%[^0-9a-zA-Z ]%', v.str) - 1)
from (values ('Order: T001.1<br />Rejection Reason: Meter Read Rejected: daily usage too high<br /><br /><a href=''http://********?ProfileId=111111&AccountId=22222&ProductId=11111&MeterId=11111''>Link to page</a>'),
             ('<b>Order: </b>Notification<br /><b>Rejection Reason: </b>Meter Read Rejected: daily usage too high<br /><br /><br /><a href=''http://********ProfileId=11111&AccountId=11111&ContractId=1111&WaterId=2222&MeterId=22222&MOT=true''>Meter page</a>')
     ) s(str) cross apply
     (values (stuff(s.str, 1, charindex('Meter Read Rejected: ', s.str) + 20, ''))) v(str)