简体   繁体   中英

How can I get a javascript function in snowflake to return one value if the argument is numeric or another value if the argument is not numeric?

My company is transitioning from an oracle database solution to snowflake data warehouse. I am converting our user defined oracle functions to snowflake user defined functions. One function we have in oracle will return a 1 if the passed value is numeric, and a 0 if the passed value is non-numeric.

To be more specific, I want to update a column (x_value) when the value column has a numeric value in it. For instance, if I have a field titled creditscore with values of 700, 599, 'no record' in rows, I need to update a field (xscore) with the numeric values and leave the non-numeric creditscore null in the xscore field.

I am new to javascript (well, not new exactly -- I did work with it all day today), and have had no luck. Here is the basic function:

CREATE OR REPLACE FUNCTION isnum(x variant)
RETURNS integer
LANGUAGE javascript
'
IF (isNan(x))
{
RETURN 1;
}
ELSE RETURN 0;
';

I have also tried typeof but get the same error, shown below:

SQL Error [1003] [42000]: SQL compilation error:
syntax error line 4 at position 0 unexpected ''

IF (isNan(x))
{
RETURN 1;
}
ELSE RETURN 0;

''.

Thank you for your assistance!

If it is Javascript then it is case sensitive.

if ( isNaN(x) ) {
  return 1;
} else {
  return 0;
}

Or you could always use a ternary operator:

return ( isNaN(x) ? 1 : 0 );

However, I have never used Snowflake before, so if it requires the JS to be formatted in a specific manner than I am unable to help with that (just the vanilla JS syntax itself).

You don't need a user defined function for this. You can use Snowflake's TRY_TO_NUMBER function.

create or replace table TEST1 (s string);

insert into TEST1 select ('Not a number');
insert into TEST1 select ('750');

select try_to_number(s) from TEST_IS_NUMBER;

Then you can insert from this select.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM