March 1, 2007 at 7:22 pm
Hi all,
I have a varchar that I need to extract a number out of.
Example:
select '13 & 9'
What can I do to that to get only the first number out? The following would be good but I'm not that lucky: 😉
select replace('13 & 9', ' &%', '')
March 1, 2007 at 7:40 pm
I'd use SUBSTRING with CHARINDEX - Is a space char always what you are going to look for?
March 1, 2007 at 7:48 pm
Yep, the format will always be:
number1 space ampersand space number1
I want number1 only.
March 1, 2007 at 7:53 pm
Whoops, forgot to mention that sometimes the filed may not have 2 numbers.
So sometimes it's like: '19 & 133'
And other times is's just: '19'
I need to make it work for both cases.
March 1, 2007 at 8:10 pm
Lol... excellent
March 1, 2007 at 8:10 pm
Got it, thanks to the suggestion of using charindex and substring. Oh and also a CASE.
March 1, 2007 at 8:10 pm
Assuming ColumnName is the name of your column (and Col1 & Col2 are additional fields)...
Select Col1, Col2, Case
When CharIndex(' ', ColumnName) = 1 Then Substring(ColumnName, 1, CharIndex(' ', ColumnName))
As FirstNumber
From TableName
... I think that will work... though you may need to subtract 1 from the index of the space (I can't remember if CharIndex is a 1-based or zero-based function).
March 1, 2007 at 8:11 pm
Yep, almost identical. Thanks.
March 2, 2007 at 6:05 am
Don't need Case if there's always a space (ack... I'm a poet and don't know it)
DECLARE @Col VARCHAR(20)
SET @Col = '13 & 9'
SELECT LEFT(@Col,CHARINDEX(' ',@Col+' ')-1)
SET @Col = '13'
SELECT LEFT(@Col,CHARINDEX(' ',@Col+' ')-1)
--Jeff Moden
Change is inevitable... Change for the better is not.
March 2, 2007 at 6:58 am
SELECT CASE WHEN ISNUMERIC() = 1 THEN
ELSE LEFT(, PATINDEX('%^[0-9]%', )-1)
END
FROM
March 2, 2007 at 7:09 am
Sorry about that, this treats less-than / greater-than symbols as HTML. I'll try that again:
SELECT CASE WHEN ISNUMERIC(Colname) = 1 THEN Colname
WHEN PATINDEX('%^[0-9]%', ColName) > 0
THEN LEFT(ColName, PATINDEX('%%', ColName) -1)
END
FROM TableName
March 2, 2007 at 4:56 pm
Uh... Don't know about anyone else, but I wouldn't use ISNUMERIC for this... case in point...
SELECT ISNUMERIC('13E5')
SELECT ISNUMERIC('13D5')
SELECT ISNUMERIC('13.5')
SELECT ISNUMERIC('13,5')
SELECT ISNUMERIC('$135')
etc... etc...
--Jeff Moden
Change is inevitable... Change for the better is not.
March 5, 2007 at 7:08 am
No kidding!! I can see 1, 3, 4, and 5....
What is '13D5'? Why does it evaluate to 1300000?
March 5, 2007 at 7:49 am
Scientific and Engineering notations...
--Jeff Moden
Change is inevitable... Change for the better is not.
Viewing 14 posts - 1 through 13 (of 13 total)
You must be logged in to reply to this topic. Login to reply