I'd like to cast a VARCHAR
to a SQL INTEGER
, supplying a default value if some value in the field would not convert properly. Something like:
sql> SELECT str FROM tbl; -- CREATE TABLE tbl (str VARCHAR(12), ...)
str
========
12345
-1
foo
sql> SELECT CAST((CASE WHEN ... THEN str ELSE '-9999' END) AS INTEGER) AS "int" FROM tbl;
int
========
12345
-1
-9999
What could I put in the ellipsis above to produce the desired results?
This question has been asked and answered on SO for many specific DBs, but I'm wondering if there's a more-or-less portable way to achieve this?