Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: How use case and cast in a query?

I want to cast VARCHAR to INT, but in my table i have some value like '???' then SQL Server launch this expcetion :

Conversion failed when converting the varchar value '????' to data type int.
Severity 16

I could convert this '???' to NULL, that's no problem, but how do that ?

I'm trying to do something like this:

INSERT INTO labbd11..movie(title, year)
SELECT movies.title, 
       CASE movies.mvyear IS '????' THEN NULL ELSE CAST (movies.mvyear AS INT)
FROM disciplinabd..movies

But nothing works ..

Any ideas guys ?

like image 571
Valter Silva Avatar asked Apr 12 '11 22:04

Valter Silva


1 Answers

You might just want to solve this in general and deal with any non-int value the same way

 INSERT INTO labbd11..movie(title, year) 
    SELECT movies.title, 
           CASE WHEN IsNumeric(movies.mvyear+ '.0e0') <> 1  THEN NULL 
                ELSE CAST (movies.mvyear AS INT) END  
      FROM disciplinabd..movies

See this question

like image 82
Conrad Frix Avatar answered Oct 23 '22 18:10

Conrad Frix