Sql How to Extract Middle of String

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 the unit number changes. How do I extract just the unit number?

Thanks!

6 Answers

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)) 
1

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
4

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))))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Robert Thorne
Author

Robert Thorne

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.