Alternative for the below update with correlated sub query in Snowflake

70 views Asked by At

In process of converting the Oracle code to Snowflake, got stuck on the below, any alternate approach for it on the Snowflake side would be appreciated

update trgt_tbl T
set (
T.cur_indicator,
T.exp_dt,
T.updt_dt
) =     (
select  'N',
S.exp_dt- 1/86400, 
sysdate
from    src_tbl S
where   S.src_id= T.src_id
and S.ind_updt  = 'U' AND scd_row_num = 1
    )
where   (T.src_id)
in  (
select  distinct X.stc_id
from    src_tbl X
where   X.ind_updt  = 'U' AND scd_row_num = 1
)
and T.cur_indicator = 'Y'

I tried the below two approaches, but not getting expected results.

First approach:

update trgt_tbl T
set
cur_indicator = 'N',
exp_dt = DATEADD('SECOND', -1,S.exp_dt),
updt_dt  = CURRENT_TIMESTAMP()
     
FROM src_tbl S
WHERE S.src_id= T.src_id
AND S.ind_updt  = 'U'
AND scd_row_num = 1
AND T.cur_indicator = 'Y';

Second approach:

update  trgt_tbl T
set T.cur_indicator  =  s.ind,
T.exp_dt = s.dt,
T.updt_dt  = s.ts
from (select    
'N' ind,
DATEADD('SECOND', -1,exp_dt ) dt, 
CURRENT_TIMESTAMP() ts,
src_id ,
ind_updt     ,
scd_row_num  
from     src_tbl ) S
where   S.src_id = T.src_id
and S.ind_updt   = 'U' 
and scd_row_num  = 1
and     (T.src_id )
in  (
select  distinct X.src_id 
from    src_tbl X
where   X.ind_updt   = 'U' AND scd_row_num = 1
)
and T.cur_indicator = 'Y';
1

There are 1 answers

0
ADITYA PAWAR On

Try this query, I refactored it based on my understanding.
And if it's still not working, Please add the sample input and expected output

update trgt_tbl T
set 
T.cur_indicator='N',
T.exp_dt=DATEADD('SECOND', -1,S.exp_dt),
T.updt_dt = getdate()
from    src_tbl S
where   S.src_id= T.src_id
and S.ind_updt  = 'U' AND scd_row_num = 1

and   (T.src_id)
in  (
select  distinct X.src_id
from    src_tbl X
where   X.ind_updt  = 'U' AND scd_row_num = 1
)
and T.cur_indicator = 'Y';