开发者

SQL how to extract middle of string

I want to only get the unit number out of this string:

'<p>The status for the Unit # 3546 has changed from % to OUTTOVENDOR</p>'

The note is always exactly the same but t开发者_如何学Che unit number changes. How do I extract just the unit number?

Thanks!


declare @String varchar(500)

set @String = '<p>The status for the Unit # 3546 has changed from % to OUTTOVENDOR</p>'

select SUBSTRING(@String, charindex('# ', @String) + 2, charindex('has changed', @String) - charindex('# ', @String) - 2)


try:

  declare @S VarChar(1000)
  Set @S = 
  '<p>The status for the Unit # 3546 has changed from % to OUTTOVENDOR</p>'
  Select Substring( @s, 
         charIndex('#', @S)+1, 
         charIndex('has', @S) - 2 - charIndex('#', @S)) 


You could do this any number of ways, use the REPLACE function to strip out either side, use SUBSTRING if you are guaranteed to know index numbers or mix a SUBSTRING with a CHARINDEX.


select substring(note, len('<p>The status for the Unit # '),4) from tbl


Something like this should work SUBSTRING(val, 30, CHARINDEX(' ', val, 30)-30)


Here's a version that uses PATINDEX. It looks for the first number in a string.

declare @MyString varchar(100) 
set @MyString = '<p>The status for the Unit # 3546 has changed from % to OUTTOVENDOR</p>'

select PATINDEX('%[0-9]%', @MyString), PATINDEX('%[^0-9]%', SUBSTRING(@MyString, PATINDEX('%[0-9]%', @MyString), len(@MyString)))

select SUBSTRING (@MyString, PATINDEX('%[0-9]%', @MyString),
    PATINDEX('%[^0-9]%', SUBSTRING(@MyString, PATINDEX('%[0-9]%', @MyString), len(@MyString))))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜