Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 CONVERT (INT, myfield) or CAST (myfield AS INT)?

Author  Topic 

techsupport14
Starting Member

18 Posts

Posted - 2014-08-04 : 14:58:22
Neither are working.

I have this function:

Create Function dbo.GetNumberic(@ItemDesc VarChar(8000))
Returns VarChar(8000)
AS
Begin
Return Left(
SubString(@ItemDesc, PatIndex('%[0-9]%', @ItemDesc), 8000),
PatIndex('%[^0-9]%', SubString(@ItemDesc, PatIndex('%[0-9]%', @ItemDesc), 8000))'X'-1)
End


and it extracts the numbers out of the alphanumeric field BUT the field is still a string and i need to match the numeric values to another table (membership number) and that's a numeric field.

So I tried the CONVERT (INT, dbo.GetNumeric(ItemDesc)) but it is not working. Nor is the CAST (dbo.GetNumeric(ItemDesc) AS INT).

Can you please help.

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2014-08-04 : 15:02:32
quote:

it is not working


Could you elaborate? Is it throwing a error? If so, please post it. Is it not showing the correct result? If so, please show us what it is doing and what it should be doing.

Tara Kizer
SQL Server MVP since 2007
http://weblogs.sqlteam.com/tarad/
Go to Top of Page

MichaelJSQL
Constraint Violating Yak Guru

252 Posts

Posted - 2014-08-04 : 21:25:49
It might be the function you are using. That function has an error in it.

Line PatIndex('%[^0-9]%', SubString(@ItemDesc, PatIndex('%[0-9]%', @ItemDesc), 8000))'X'-1)

The 'X'-1)

. it will also only find the first numeric sequence in a string. but if that is all you need, you're good. Could just be the error.

You might try something like the following in the function body:

DECLARE @AlphaNUmeric Varchar(25) = 'XDHDH123hh$4ll'
DECLARE @I int = 1
DECLARE @Return varchar(100) = ''

WHILE @I < LEN(@AlphaNUmeric)
BEGIN
SELECT @Return = @Return + CASE WHEN ASCII(SUBSTRING(@AlphaNUmeric,@I,1)) BETWEEN 48 and 57 THEN SUBSTRING(@AlphaNUmeric,@I,1) ELSE '' END
SET @I = @I + 1
END

SELECT CAST(@Return as INT)



Go to Top of Page

techsupport14
Starting Member

18 Posts

Posted - 2014-08-05 : 00:03:01
Thank you. I figured it out :)
Go to Top of Page

ScottPletcher
Aged Yak Warrior

550 Posts

Posted - 2014-08-05 : 13:03:44
Yeah, pretty clear the code meant to be this:

PatIndex('%[^0-9]%', SubString(@ItemDesc, PatIndex('%[0-9]%', @ItemDesc), 8000)+'X')-1)
Go to Top of Page
   

- Advertisement -