Get null if non numeric or the actual numeric value in TSQL

Vladimir picture Vladimir · Nov 14, 2012 · Viewed 8.8k times · Source

I'm trying to get the numeric value of a string if isnumeric() function returns 1 or NULL if it returns 0. But I only get if it's numeric I get 1 or null if non numeric. Is it possible to return the numeric value (instead of 1) using something like the code below?

select '14-154877-0' as actual_string, replace('14-154877-0', '-', '') as numeric_value, nullif(isnumeric(replace('14-154877-0', '-', '')), 0) as numeric_value_or_null /* Here I wold like to return the numeric value instead of 1 */

select 'some text' as actual_string, replace('some text', '-', '') as numeric_value, nullif(isnumeric(replace('some text', '-', '')), 0) as numeric_value_or_null /* OK */

Sample data

The insert statements are a result of the excel concatenation function.

As sugested, I used the case expression and the try_convert() (for MSSQL 2012) function and they work fine. Is there a better way of doing this kind of insert?

if object_id('tempdb..#temp_table') is not null
    begin
        drop table #temp_table;
    end;

create table #temp_table (
        int_column int,
        varchar_column varchar(50)
    );

insert into #temp_table (int_column, varchar_column) values (case when isnumeric(replace('111----111', '-', '')) = 1 then replace('111----111', '-', '') end, 'string data 1');
insert into #temp_table (int_column, varchar_column) values (case when isnumeric(replace('text', '-', '')) = 1 then replace('text', '-', '') end, 'string data 2');
insert into #temp_table (int_column, varchar_column) values (try_convert(int, replace('258--', '-', '')), 'string data 3');
insert into #temp_table (int_column, varchar_column) values (try_convert(int, replace('123', '-', '')), 'string data 4');

select * from #temp_table;

/*
    |   int_column  |   varchar_column  |
    |   111111      |   string data 1   |
    |   NULL        |   string data 2   |
    |   258         |   string data 3   |
    |   123         |   string data 4   |
*/

Answer

Tim Schmelter picture Tim Schmelter · Nov 14, 2012

Perhaps:

SELECT value as actual_string
, replace(value, '-', '') as numeric_value
, CASE ISNUMERIC(replace(value, '-', ''))
  WHEN 1 THEN CAST(replace(value, '-', '') AS FLOAT)
  ELSE NULL END AS numeric_value_or_null
FROM TableName

Fiddle inside