5

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 ?

Scotty.NET
  • 12,533
  • 4
  • 42
  • 51
Valter Silva
  • 16,446
  • 52
  • 137
  • 218

5 Answers5

10

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

Community
  • 1
  • 1
Conrad Frix
  • 51,984
  • 12
  • 96
  • 155
5

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.

Justin Cave
  • 227,342
  • 24
  • 367
  • 384
0
    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
Nitin Midha
  • 2,258
  • 20
  • 22
0
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
amit_g
  • 30,880
  • 8
  • 61
  • 118
0

You can also use:

CAST(NULLIF(movies.mvyear,'????') AS INT)
Martin Smith
  • 438,706
  • 87
  • 741
  • 845