我不知道哪里出了问题。
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') ));
任务成功状态:
发布于 2022-09-03 07:56:21
会话变量只适用于它在其中创建的会话。
SQL变量是会话的私有变量。当雪花会话关闭时,将删除在会话期间创建的所有变量。这意味着没有人可以访问在另一个会话中设置的用户定义的变量,并且当会话关闭时,这些变量将过期。
任务使用自己的会话执行,因此:
where s.start_time >= to_timestamp( getvariable('L_LAST_CONTROL_DT') ));
是与空值的比较:
where s.start_time >= NULL
这总是不正确的,选择0行。
对一个全新的会话进行快速测试:
SELECT getvariable('L_LAST_CONTROL_DT')
-- NULL
当使用$
访问会话变量时,可以更容易地发现
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;
https://stackoverflow.com/questions/73590494
复制相似问题