0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[Snowflake] UDFを試してみた (スカラーUDF編)

Posted at

UDFの種類

snowflakeのudfには以下の2種類があるようです。[参考]
今回はこのうちScalar UDFを試してみます

  • Scalar UDF
    入力行ごとに1つの出力行を返す
  • Tabular UDF
    入力行ごとに表形式の値を返す

UDFの定義

生年月日を受け取って年齢を計算するUDFの定義がこちらです。Pythonで書いています。
Python, Java, Javascript, Scala などが使用できるようです。[参考]

create or replace function birthday2age(birthday string)
returns int
language python
runtime_version = '3.9'
handler = 'main'
as
$$
import datetime
def main(birthday):
    today = datetime.date.today()
    birthday = datetime.datetime.strptime(birthday, "%Y-%m-%d")
    age = (int(today.strftime("%Y%m%d")) - int(birthday.strftime("%Y%m%d"))) // 10000
    return age
$$;

このコードを実行すると、実行時に指定している DATABASE.SCHEMA の下にUDFが作成されています。

作成したUDFの利用

作成したUDFはSELECT文の中で利用できます

SELECT BIRTHDAY2AGE('1999-01-01')
-> 24
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?