我想将VARCHAR转换为INT,但在我的表中我有一些像'???'的值然后SQL Server启动此expcetion:
Conversion failed when converting the varchar value '????' to data type int.
Severity 16
我可以转换这个'???'为NULL,这没问题,但是怎么做?
我正在尝试做这样的事情:
INSERT INTO labbd11..movie(title, year)
SELECT movies.title,
CASE movies.mvyear IS '????' THEN NULL ELSE CAST (movies.mvyear AS INT)
FROM disciplinabd..movies
但没有任何作用..
任何想法的人?
答案 0 :(得分:8)
您可能只想解决这个问题并以相同的方式处理任何非int值
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
请参阅此question
答案 1 :(得分:3)
我相信你会想要像
这样的东西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
您希望CASE语句返回VARCHAR(MVYEAR
或NULL),然后您希望CAST对CASE的结果进行操作。
答案 2 :(得分: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
答案 3 :(得分: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
答案 4 :(得分:0)
您也可以使用:
CAST(NULLIF(movies.mvyear,'????') AS INT)