简体   繁体   中英

Trying to use CASE WHEN and ISNUMERIC

So, I'm trying to validate a column 'id' in the table 'tableId', which has the following

|id|
12345678
0012345678
A12345
B12345

I'm trying to create a 2nd column called id2 which would be:

|id2|
12345678
12345678
A12345
B12345

So that I can know, after using COUNT + DISTINCT, that there are duplicates that just happen to have 0s left of the number, but are in fact the same IDs.

I tried to use CASE WHEN with ISNUMERIC and CAST as numeric, as some sort of error management that returns the same value (the ones that have a non-numeric character such as the last 2) in case it isn't numeric and, if it is, it'll cast it to numeric and return the numeric value without the 0s on the left. However, it returns the error

Error converting data type varchar to numeric.

The code:

select id,
        case when ISNUMERIC(id)=0 then id else CAST(id as numeric) end as id2
        from tableId

In Excel I'd have used something like =IF(ISNUMBER(id),VALUE(id),id), but I can't seem to get it right on SQL Server 2012.

Thanks in advance!

Diego

Use try_cast() instead:

select id, TRY_CAST(id as numeric) id2
from tableId

Use below query to get distinct count

select count(distinct( 
   case when try_cast(ID as numeric) is null 
         then ID else cast(try_cast(ID as numeric) as char) end)) as New_ID  
from your_Table

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM