Valter Silva
Valter Silva

Reputation: 16656

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 ?

Upvotes: 5

Views: 118259

Answers (5)

Martin Smith
Martin Smith

Reputation: 453152

You can also use:

CAST(NULLIF(movies.mvyear,'????') AS INT)

Upvotes: 0

Conrad Frix
Conrad Frix

Reputation: 52645

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

Upvotes: 11

amit_g
amit_g

Reputation: 31250

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

Upvotes: 0

Nitin Midha
Nitin Midha

Reputation: 2268

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

Upvotes: 0

Justin Cave
Justin Cave

Reputation: 231661

I believe you would want something like

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

You want your CASE statement to return a VARCHAR (either the MVYEAR or NULL) and then you want the CAST to operate on the result of the CASE.

Upvotes: 5

Related Questions