I have a case statement to rectify one business logic in snowflake:
INSERT INTO DB.table_b
SELECT
CASE
WHEN UPPER(emp) <> LOWER(emp) THEN NULL
WHEN emp IS NULL THEN nullif(emp, 'NULL')
ELSE emp
END AS emp_no
FROM
DB.table_a;
The ‘table_a’ content as below :
emp
-------
ABCD
NULL
''
23
It contains character string, null, empty and numbers. So, the requirement is to take only numbers and empty values from the case statement since the column emp_no in ‘table_b’ is numeric type. In source table if the column value is string then we have to insert NULL value. But as the ‘table_b’ column is of type ‘numeric’ the null value is not getting inserted and getting following error
Numeric value ” is not recognized
4
Answers
you can not use
IS_INTEGER
but for VARCHAR(16777216) it isn’t supportedSo a regular expression would be better
Using TRY_TO_NUMBER:
As Lukasz mentions you should use the
TRY_TO_x
functions (TRY_TO_NUMERIC, TRY_TO_DOUBLE) as these safely handle parsing the types, and return NULL if the parse fails. The extra note I will add is that both NUMBER/NUMERICs and DOUBLEs will parse0.1234
but get different results, which you didn’t mention as caring about, but I think is worth noting, so I am adding an extra answer to point the difference out.The CTE is just to get the values into the SQL:
You can test for amp being string and set the string to NULL. Only numeric values will go into the second case statement.