Abs
Abs

Reputation: 57916

Conversion failed when converting the nvarchar to int

I have a field which is varchar and contains numbers and dates as strings. I want to update all numbers in this field that is greater than 720. I have attempted firstly to do a select but I get this error:

Conversion failed when converting the nvarchar value '16:00' to data type int.

This is my query:

select id, case(isnumeric([other08])) when 1 then [other08] else 0 end
from CER where sourcecode like 'ANE%' --and other08 > 720

It fails when I uncomment the last part.

I am trying to get all numerics greater than 720, but I can't do the comaprison. It also fails when casting and converting.

Thanks all for any help

Upvotes: 3

Views: 10715

Answers (2)

Winston Smith
Winston Smith

Reputation: 21884

You also need to perform the checks and conversion in the WHERE clause:

SELECT 
       id, 
       CASE WHEN isnumeric([other08]) = 1 THEN CAST([other08] AS INT) ELSE 0 END
FROM   CER 
WHERE  sourcecode LIKE 'ANE%' 
AND CASE WHEN isnumeric([other08]) = 1 THEN CAST([other08] AS INT) ELSE 0 END > 720

Upvotes: 7

dsolimano
dsolimano

Reputation: 8986

You need to use IsNumeric in your where clause, to avoid trying to compare strings to the number 720. Eg:

select id, case(isnumeric([other08])) when 1 then [other08] else 0 end
from CER 
where sourcecode like 'ANE%' and ISNUMERIC(other08) = 1 and other08 > 720

EDIT

As @Abs pointed out, the above approach won't work. We can use a CTE to compute a reliable field to filter on, however:

WITH Data AS (
  select id
    , case WHEN isnumeric([other08]) THEN CAST([other08] AS int) else 0 end AS FilteredOther08
    , CER.* 
  from CER 
  where sourcecode like 'ANE%'
)
SELECT *
FROM Data
WHERE [FilteredOther08] > 720

Upvotes: 2

Related Questions