This SQL statement is merging data from a staging table into a dimension table to handle slowly changing dimensions. It uses a DECODE function to determine a surrogate key for new or changed records. It then performs an UPDATE to existing dimension records setting the end date and flag when data has changed, and an INSERT for new records to populate the dimension with the current data.
This SQL statement is merging data from a staging table into a dimension table to handle slowly changing dimensions. It uses a DECODE function to determine a surrogate key for new or changed records. It then performs an UPDATE to existing dimension records setting the end date and flag when data has changed, and an INSERT for new records to populate the dimension with the current data.
This SQL statement is merging data from a staging table into a dimension table to handle slowly changing dimensions. It uses a DECODE function to determine a surrogate key for new or changed records. It then performs an UPDATE to existing dimension records setting the end date and flag when data has changed, and an INSERT for new records to populate the dimension with the current data.
USING ( SELECT DECODE(s.scd_row_type_id,1,-6789,m.product_sid) as product_sid,
PRODUCT_ID, PRODUCT_CATEGORY_ID, PRODUCT_NAME, PRODUCT_DESCRIPTION, PRICE, PRICE_EFFECTIVE_DATE, LAST_MODIFIED_DATE, CREATED_DATE, m.scd_row_type_id FROM (SELECT dp.product_sid, sp.PRODUCT_ID, sp.PRODUCT_CATEGORY_ID, sp.PRODUCT_NAME, sp.PRODUCT_DESCRIPTION, sp.PRICE, sp.PRICE_EFFECTIVE_DATE, sp.LAST_MODIFIED_DATE, sp.CREATED_DATE, CASE WHEN dp.product_id IS NULL THEN 1 WHEN (dp.product_category_id != sp.product_category_id OR dp.product_name != sp.product_name OR DP.PRODUCT_DESCRIPTION != sp.product_description OR dp.price != sp.price OR dp.price_effective_date != sp.price_effective_date) THEN 2 ELSE 0 END AS scd_row_type_id FROM stg_product sp LEFT JOIN Dim_product dp ON (sp.product_id = dp.product_id and dp.is_current_row = 'Y') ) m JOIN scd_row_type s ON (s.scd_row_type_id <= m.scd_row_type_id) ) mp ON (p.product_sid = mp.product_sid) when matched then update set P.EFFECTIVE_END_DATE = mp.LAST_MODIFIED_DATE, is_current_row = 'N', updated_date = sysdate when NOT matched then insert (P.PRODUCT_SID,P.PRODUCT_ID,P.PRODUCT_CATEGORY_ID, P.PRODUCT_NAME, P.PRODUCT_DESCRIPTION, P.PRICE, p.PRICE_EFFECTIVE_DATE,P.LAST_MODIFIED_DATE, p.effective_start_date,P.EFFECTIVE_END_DATE,is_current_row, created_date, updated_date ) values (s_dim_product.nextval,mp.PRODUCT_ID,mp.PRODUCT_CATEGORY_ID,mp.PRODUCT_NAME, mp.PRODUCT_DESCRIPTION, mp.PRICE,mp.price_effective_date, mp.LAST_MODIFIED_DATE,mp.last_modified_date, to_date('2099-12-31 00:00:00','YYYY-MM-DD HH24:MI:SS'),’Y', sysdate,sysdate); commit;
Ultimate Snowflake Architecture for Cloud Data Warehousing: Architect, Manage, Secure, and Optimize Your Data Infrastructure Using Snowflake for Actionable Insights and Informed Decisions (English Edition)