简体   繁体   English

如果参数是数字,我怎样才能让雪花中的 javascript 函数返回一个值,如果参数不是数字,我如何返回另一个值?

[英]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.我的公司正在从 oracle 数据库解决方案过渡到雪花数据仓库。 I am converting our user defined oracle functions to snowflake user defined functions.我正在将我们的用户定义的 oracle 函数转换为雪花用户定义的函数。 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.我们在 oracle 中有一个函数,如果传递的值为数字,则返回 1,如果传递的值为非数字,则返回 0。

To be more specific, I want to update a column (x_value) when the value column has a numeric value in it.更具体地说,当值列中有数值时,我想更新列 (x_value)。 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.例如,如果我有一个名为 creditscore 的字段,其值为 700, 599,行中的“无记录”,我需要使用数值更新字段 (xscore),并将 xscore 字段中的非数字 creditscore 保留为空。

I am new to javascript (well, not new exactly -- I did work with it all day today), and have had no luck.我是 javascript 的新手(好吧,完全不是新的——我今天一整天都在用它),而且运气不好。 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:我也试过 typeof 但得到同样的错误,如下所示:

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.如果它是 Javascript 那么它是区分大小写的。

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).但是,我以前从未使用过 Snowflake,因此如果它需要以特定方式格式化 JS,我将无能为力(仅是 vanilla JS 语法本身)。

You don't need a user defined function for this.为此,您不需要用户定义的函数。 You can use Snowflake's TRY_TO_NUMBER function.您可以使用 Snowflake 的 TRY_TO_NUMBER 函数。

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.然后您可以从此选择插入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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