I’m trying find the best way to remove nonnumerical data from a varchar in SQL e.g.
'(082) 000-0000' to '0820000000' or '+2782 000 0000' to '0820000000'
The difficulty is i’m not always sure what number formats are coming in, as shown above, so I’d like like everything that is not a number removed essentially.
Update:
From what you guys have said this is a little spike done:
declare @Num varchar(20) set @Num = ' + (82) 468 6152 ' --strip nonnumrical data out of @num print @Num set @Num = replace(@Num, ' ', '') set @Num = replace(@Num, '+', '') set @Num = replace(@Num, '-', '') set @Num = replace(@Num, '(', '') set @Num = replace(@Num, ')', '') print @Num
Couldn’t get the replace [^0-9] expression right though.
If you’re using SQL Server 2005 or newer then your best option is to create a user-defined CLR function and use a regular expression to remove all non-numeric characters.
If you don’t want to use a CLR function then you could create a standard user-defined function. This will do the job although it won’t be as efficient:
And then select from your table like so: