How to update statement in snowflake using with CTE (WITH CTE- common_table_expression)?

Viewed 457

I am trying to update the one field in the final table. i have logic down here. I have to update the last_version_flag when it meets certain scenario. how to use WITH CTE concept in snowflake. thank you in advance.

update  dw.tb_fidctp_order
set     last_version_flag = 'N'
from    dw.tb_fidctp_order
where (with my_cte as (
select  order_id, MAX(cast(VERSION as NUMBER(18,0))) as max_version
from    stg.tb_fidctp_order_input 
group by order_id))
DW.tb_fidctp_order.order_id = my_cte.order_id and DW.tb_fidctp_order.version < my_cte.max_version
1 Answers

The correct syntax is UPDATE target_table SET col_name = value FROM additional_tables WHERE condition :

CREATE TABLE tb_fidctp_order(version INT, order_id INT, last_version_flag  TEXT);
CREATE TABLE tb_fidctp_order_input(version INT,order_id INT, last_version_flag TEXT);


update  tb_fidctp_order
set     last_version_flag = 'N'
from (
         WITH cte AS (
           select  order_id, MAX(cast(VERSION as NUMBER(18,0))) as max_version
           from    tb_fidctp_order_input 
          group by order_id
          )
          SELECT * FROM cte
     ) AS my_cte
where  tb_fidctp_order.order_id = my_cte.order_id 
  and tb_fidctp_order.version < my_cte.max_version;
Related