[英]Snowflake CRON Task not inserting data into table
我不知道哪里出了問題。
use database test_db;
use schema test_Schema;
use warehouse test_wh;
--to get the past one year date when I execute the code
set l_last_control_dt =
(
select
ifnull( dateadd( hour, -4, max( start_time ) ), dateadd( month, -13, current_timestamp() ) ) as last_control_dt
from
test_db.test_Schema;.warehouse_metering_history
);
----count of rows where start time from warehouse_metering_history greater than l_last_control_dt
set l_row_count =
(
select count(*)
from
snowflake.account_usage.warehouse_metering_history where
s.start_time >= to_timestamp( $l_last_control_dt )
);
CREATE or replace TASK task_load_warehouse_metering_tbl
WAREHOUSE = test_wh
SCHEDULE = 'USING CRON */5 * * * * UTC'
AS
INSERT into
test_db.test_schema.warehouse_metering_tbl
(
select
current_account() as account_name
,current_region() as region_name
,s.start_time
,s.end_time
,s.warehouse_id
,s.warehouse_name
,s.credits_used
,s.credits_used_compute
,s.credits_used_cloud_services
,'warehouse_metering_history'
,getvariable('L_ROW_COUNT')
,to_timestamp( sysdate() )
from
snowflake.account_usage.warehouse_metering_history s
where
s.start_time >= to_timestamp( getvariable('L_LAST_CONTROL_DT') ));
任務成功狀態:
Session 變量僅適用於創建它的 session。
SQL 變量是 session 的私有變量。 當雪花 session 關閉時,在 session 期間創建的所有變量都將被刪除。 這意味着沒有人可以訪問已經在另一個 session 中設置的用戶定義變量,並且當 session 關閉時,這些變量就會過期。
任務使用自己的 session 執行,因此:
where s.start_time >= to_timestamp( getvariable('L_LAST_CONTROL_DT') ));
是與 NULL 值的比較:
where s.start_time >= NULL
這總是不正確的,選擇了 0 行。
對全新的 session 進行快速測試:
SELECT getvariable('L_LAST_CONTROL_DT')
-- NULL
使用$
訪問 session 變量時,可以更容易地發現這一點:
SELECT $L_LAST_CONTROL_DT
-- Error: Session variable '$L_LAST_CONTROL_DT' does not exist (line 1)
使用雪花腳本塊和塊變量的解決方案:
CREATE or replace TASK task_load_warehouse_metering_tbl
WAREHOUSE = test_wh
SCHEDULE = 'USING CRON */5 * * * * UTC'
AS
$$
DECLARE
l_last_control_dt TIMESTAMP := (
SELECT
ifnull( dateadd( hour, -4, max( start_time ) ),
dateadd( month, -13, current_timestamp() ) ) as last_control_dt
FROM test_db.test_Schema.warehouse_metering_history);
l_row_count INTEGER;
BEGIN
l_row_count := (SELECT COUNT(*)
FROM snowflake.account_usage.warehouse_metering_history
WHERE s.start_time >= :l_last_control_dt);
INSERT INTO test_db.test_schema.warehouse_metering_tbl
-- (col_name1, col_name2, col_name3, ...)
SELECT
current_account() as account_name
,current_region() as region_name
,s.start_time
,s.end_time
,s.warehouse_id
,s.warehouse_name
,s.credits_used
,s.credits_used_compute
,s.credits_used_cloud_services
,'warehouse_metering_history'
,:l_row_count
,to_timestamp( sysdate() )
FROM snowflake.account_usage.warehouse_metering_history s
WHERE s.start_time >= :l_last_control_dt);
END;
$$
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.