views:

62

answers:

6

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!

A: 

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.

ChrisCM
+4  A: 
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)
Joe Stefanelli
A: 
select substring(note, len('<p>The status for the Unit # '),4) from tbl
Beth
This makes the bad assumption that unit number is always 4 digits.
Joe Stefanelli
yes, he said it's always exactly the same, so I believed him. charIndex('has changed') is better.
Beth
I read the question to mean the text was always the same, not necessarily the unit number length.
Joe Stefanelli
yeah, I can see that, too. I tend to take phrases like 'the same' literally. As I said, the charindex() is better.
Beth
+1  A: 

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)) 
Charles Bretana
I'm iffy on the cast to integer - we don't know that unit numbers are always int (e.g., could be unit `362A`).
RedFilter
take that out then... (edited )
Charles Bretana
A: 

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

Eugene Kuleshov
A: 

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