<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Luke Haakenson on Medium]]></title>
        <description><![CDATA[Stories by Luke Haakenson on Medium]]></description>
        <link>https://medium.com/@lukehaakenson?source=rss-ac7815031021------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*wDBupjPX8AKQoYaf</url>
            <title>Stories by Luke Haakenson on Medium</title>
            <link>https://medium.com/@lukehaakenson?source=rss-ac7815031021------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 13:59:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lukehaakenson/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[[Tips for Snowflake] Framework for Ingesting Small Files into Snowflake]]></title>
            <link>https://medium.com/@lukehaakenson/tips-for-snowflake-framework-for-ingesting-small-files-into-snowflake-2c85b59b5f67?source=rss-ac7815031021------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c85b59b5f67</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[procedure]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[snowflake]]></category>
            <dc:creator><![CDATA[Luke Haakenson]]></dc:creator>
            <pubDate>Tue, 13 May 2025 18:23:40 GMT</pubDate>
            <atom:updated>2025-06-02T14:51:36.808Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*ZHr7FPeOpkeyo8jFgbb4MA.png" /></figure><p>When you are initially selecting your ingest pattern for Snowflake there are a few things to consider like the number, size, and per-file charge depending on what path you are choosing.</p><p>Most typically I have used a Snowpipe for our projects when we are able to batch our files into a reasonable size that Snowflake likes, at least 10MB, but ideally larger 100–250MB files if possible.</p><p>However, there were cases for ingesting very small files (100Kb) in size, with only one or two arriving per week. A Snowpipe ‘could’ be used, but it is not efficient use of the mechanism for cases like this.</p><p><strong>Summarizing the Solution — Use Serverless Task w/Procedures</strong></p><p>So, what can you do? In this case I ended up creating a robust Java procedure that checks for new files, iterates if there are more than one, and runs on a scheduled serverless task. It can be reused for different tables and supports using less complex COPY INTO or cases where you need more complex sql by using INSERT INTO.</p><p>Full example below.</p><p><strong>Step 1: Create your Stage</strong></p><p>Example of a raw landing table, the file could be any type, my situation was using CSV where we needed the raw data stored.</p><pre>CREATE OR REPLACE TABLE DB.SCHEMA.RAW_LANDING AS<br>SELECT<br>    STG.METADATA$START_SCAN_TIME AS LOADED_AT,<br>    STG.METADATA$FILENAME as FILENAME,<br>    STG.METADATA$FILE_ROW_NUMBER as FILE_ROW_NUMBER,<br>    STG.$1 AS ORIGINAL_TEXT_RAW<br>FROM @DB.EXTERNAL_STAGES.RAW_DATA_STAGE<br>(FILE_FORMAT =&gt; DB.FILE_FORMATS.FORMAT_TYPE, PATTERN =&gt; &#39;.*.csv&#39;) STG;</pre><p><strong>Step 2: Procedure — Java (Copies Latest File-s in Stage)</strong></p><p>Here is the main part, you can edit this code as-needed for your own situations.</p><p>Here is what it does in summary:</p><ul><li>First it selects the latest files based on the current_date() the procedure will run, ideally this be the day it is known that files drop as expected into blob storage (like S3).</li><li>Second with the files selected, a loop is used, in this step it will check to see if the file was already ingested previously, since we are not using a Snowpipe we need behavior that is similar. IF the file was already ingested, it will input this for the final return string (in a case where all of them were previously ingested, it will stop here otherwise will continue)</li><li>Lastly the COPY command that you input is executed. My example uses a more complex SQL statement using INSERT INTO. However, a COPY INTO could be used as well for less complex requirements.</li><li>(NOTE that both the second and third steps use the variable latest_file, my INSERT statement is an example that I ended up using in a scenario you will likely need to modify it)</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fdf7b46d1e24bbe01f18d72a19f01bc9/href">https://medium.com/media/fdf7b46d1e24bbe01f18d72a19f01bc9/href</a></iframe><p><strong>Step 3: Create a Serverless Task</strong></p><p>For scenarios like this where you will only need a warehouse for less than a minute, that would not even fully use an entire user-managed warehouse, a serverless task can be used.</p><p>A serverless task is also recommended for very predictable scenarios such as this example.</p><ul><li>SERVERLESS_TASK_MIN_STATEMENT_SIZE = ‘XSMALL’ (to ensure the smallest warehouse is used)</li><li>TARGET_COMPLETE_INTERVAL = ’30 SECONDS’ (if you know how long it takes to run on average, this could be seconds, minutes, or hours)</li></ul><pre>CREATE OR REPLACE TASK DB.SCHEMA.TSK1<br>    SCHEDULE = &#39;USING CRON 35 7 * * 1 US/Eastern&#39; //735am M (expected file drop)<br>    SERVERLESS_TASK_MIN_STATEMENT_SIZE = &#39;XSMALL&#39;<br>    TARGET_COMPLETION_INTERVAL = &#39;30 SECONDS&#39;<br>AS<br>CALL DB.FUNCTIONS.COPY_LATEST_FILEv2();</pre><p>And that’s it!</p><p>A simple and elegant solution to automating a COPY INTO or INSERT for very small data sets.</p><p>EDIT: 6–2–25 ; in testing the old v2 variant was running far too long, I have created a new version for the article. ingested and processed files are added to sets with another while loop. Testing reduced run time from 1–2m to 2–3s. For each SQL statement you will need to edit and adjust for your scenario.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c85b59b5f67" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Tips for Snowflake] A Data Quality Framework using SQL Scripting]]></title>
            <link>https://medium.com/@lukehaakenson/tips-for-snowflake-a-data-quality-framework-using-sql-scripting-1ef3beb56928?source=rss-ac7815031021------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ef3beb56928</guid>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-quality]]></category>
            <category><![CDATA[sql-scripting]]></category>
            <category><![CDATA[data-quality-framework]]></category>
            <dc:creator><![CDATA[Luke Haakenson]]></dc:creator>
            <pubDate>Tue, 18 Feb 2025 23:27:46 GMT</pubDate>
            <atom:updated>2025-03-02T18:06:00.823Z</atom:updated>
            <content:encoded><![CDATA[<p>Free use coding framework idea from my projects utilizing Snowflake itself for Data Quality Monitoring</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PBEVH6F9tB5BUTYsfZlWRg.jpeg" /></figure><h3><strong>Overview</strong></h3><p>There are many different options for performing Data Quality checks for Engineering pipelines, such as using procured applications that you and your team have access to like Great Expectations, SODA, Monte Carlo, DBT unit testing, etc.</p><p>However, when you might not have those options available you may need to get a little more creative and use whatever is available to you. If you are using Snowflake, for example, thankfully it offers a lot of options for doing just that with System Data Quality Metrics directly on a Table <em>or</em> creating more Robust UDFs utilizing SQL, Python, or Java for example.</p><p>As an experiment, for a project, our particular use case did not have anything else available to use but Snowflake itself. And thus, I created a SQL Script UDF Data Quality Framework that I will go through below on how to setup yourself.</p><h3><strong>Setup</strong></h3><p>Before beginning this setup, it&#39;s important to acknowledge that not all Data Quality policies are the same for each team or client. I have made this script as simple as possible to understand and setup, so that you may use the included types of Data Quality checks or run with the idea to modify it as you see fit.</p><p><strong>Step 1: Create your Data Quality Results Table</strong></p><p>(Depending on if you modify the main procedure, adjust this table output as needed)</p><pre>CREATE OR REPLACE TABLE YOUR_DB.YOUR_SCHEMA.DATA_QUALITY_RESULTS_TBL(<br>TABLE_NAME VARCHAR, <br>CHECK_DATE DATE,<br>ROW_KEY ARRAY,<br>DUPLICATE_COUNT INT, <br>NULL_COUNT INT,<br>FRESHNESS_DAYS_SINCE_LAST_UPDATE INT, <br>CHECK_RUN_TIMESTAMP DATETIME<br>);</pre><p><strong>Step 2: Create your Data Quality Config Table</strong></p><p>(Depending on if you modify the main procedure, adjust this table output as needed)</p><pre>CREATE OR REPLACE TABLE YOUR_DB.YOUR_SCHEMA.DATA_QUALITY_CONFIG_TBL (<br>FULL_TABLE_LINK_NAME VARCHAR,<br>DATABASE_NAME VARCHAR,<br>SCHEMA_NAME VARCHAR,<br>TABLE_NAME VARCHAR,<br>COMPLETE_RECORD_SQL_LIST VARCHAR,<br>NULL_COLUMN_CHECK VARCHAR<br>);</pre><p>FULL_TABLE_LINK_NAME = A string of the full snowflake link to a table to perform data quality checks on</p><p>DATABASE_NAME = A string of only the Database Name</p><p>SCHEMA_NAME = A string of only the Schema Name</p><p>TABLE_NAME = A string of only the Table Name</p><p>COMPLETE_RECORD_SQL_LIST = A string containing partial SQL used in conjunction with Dynamic SQL to define your ‘complete’ record</p><p>NULL_COLUMN_CHECK = A string of the name of a column in the table you are checking that you wish to check for nulls</p><pre>--Example<br>INSERT INTO TABLE YOUR_DB.YOUR_SCHEMA.DATA_QUALITY_PROVIDED_TBL <br>(FULL_TABLE_LINK_NAME, <br>DATABASE_NAME, <br>SCHEMA_NAME, <br>TABLE_NAME, <br>COMPLETE_RECORD_SQL_LIST, <br>NULL_COLUMN_CHECK)<br>VALUES <br>(&#39;YOUR_DB.YOUR_SCHEMA.PATIENT_DATA_TBL&#39;, <br>&#39;YOUR_DB&#39;, <br>&#39;YOUR_SCHEMA&#39;, <br>&#39;PATIENT_DATA_TBL&#39;, <br>&#39;USER_TYPE IS NOT NULL AND DATE_OF_BIRTH IS NOT NULL AND VISIT_DATE IS NOT NULL&#39;, <br>&#39;UNIQUE_PATIENT_ID&#39;);</pre><p><strong>Step 3: Create the Data Quality Procedure</strong></p><p>(Adjust this procedure as needed)</p><p>Settings: Adjust the following to your environment setup</p><ul><li>Replace YOUR_DB.YOUR_SCHEMA throughout where you are creating your tables and the procedure</li><li>The process creates temporary tables to produce a result, if any, which you will also need to choose where they will be created</li><li>check_date DATE — this variable determines the date period you are actually checking<br> check_date_fresh DATE — this variable is for checking the freshness of the date comparing the check_date you have chosen. So if for example your data is expected every 2 hours use the INTERVAL constant to define it<br> date_column STRING — this assumes your date_column is named the same across the series of tables<br> unique_row_key STRING — this assumes your primary key row is named the same across all tables</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5044c13e69e0ee6010e4c615360932f7/href">https://medium.com/media/5044c13e69e0ee6010e4c615360932f7/href</a></iframe><p><strong>Alternate Version (Combined CTE Data Checks)</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/34f1fc69022cdfb668bcc03b294f4948/href">https://medium.com/media/34f1fc69022cdfb668bcc03b294f4948/href</a></iframe><h4>Concluding Thoughts</h4><p>It&#39;s important to keep in mind a ‘Data Quality’ check is not always a one size fits all. This is one such method you could use that contains the more common checks — I have demonstrated that you can use Snowflake for outside the box purposes when the situation calls for it. Something like this could also be setup either in a ‘Side Loaded’ or ‘Circuit Breaker’ fashion.</p><p>I have tested this on very large, wide-modeled tables with millions of rows and while it did run performatively well, depending on the size of the table a SQL Script like this may not be exactly what you will need especially if you are running it daily. That being said this performs best with smaller chunks of data and tables.</p><p>In future articles I will explore using JavaScript and Python as alternatives.</p><p>If you’d like to connect you can also find me over on <a href="https://www.linkedin.com/in/luke-haakenson/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ef3beb56928" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Tips for Snowflake] How to make an Iterative Merge in Snowflake]]></title>
            <link>https://medium.com/@lukehaakenson/how-to-make-an-iterative-merge-in-snowflake-128a1bc34f1f?source=rss-ac7815031021------2</link>
            <guid isPermaLink="false">https://medium.com/p/128a1bc34f1f</guid>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[pipeline]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Luke Haakenson]]></dc:creator>
            <pubDate>Fri, 04 Oct 2024 16:56:17 GMT</pubDate>
            <atom:updated>2025-02-04T20:53:20.281Z</atom:updated>
            <content:encoded><![CDATA[<h4>Framework for more complex Merge Usage</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*_cuGnXKZL-9qH74r5WUOFA.png" /></figure><p>The ubiquitous Merge is often the last piece of the puzzle in my Snowflake pipelines. Whether for Inserting, Updating, and Deleting or a combination they are handy for performing more complex transformations into “finalized” target tables from staging areas.</p><p>One particular interesting problem, that I had to write a solution for, involved a way create a lookup table derived from two different event profile types. One for the ‘creation’ of the profile and subsequent ‘change’ for the profile fields that were updated.</p><p>This all needed to be recorded in separate historical tables, and lastly one “final” table that may slowly change dimensions over time with more profiles and updates, while containing all useful information about that profile.</p><p>One particular problem in utilizing a Merge in this situation is when multiple changes that potentially occur back-to-back within minutes or hours, or throughout the day. If the situation calls for it, you might only need the last change that occurred, but if data capture does not include any of the previous changes and only a specific one then you have a problem.</p><p><strong>Snowflake SQL Scripting</strong></p><p>There is a way to do this with Snowflake SQL Scripting which is fairly similar to other languages with its own quirks baked in. An example from the <a href="https://docs.snowflake.com/en/developer-guide/stored-procedure/stored-procedures-snowflake-scripting">Snowflake Documentation</a> below.</p><pre>DECLARE<br>  res1 RESULTSET;<br>BEGIN<br>res1 := (CALL my_procedure());<br>LET c1 CURSOR FOR res1;<br>FOR row_variable IN c1 DO<br>  IF (row_variable.col1 &gt; 0) THEN<br>    ...;<br>  ELSE<br>    ...;<br>  END IF;<br>END FOR;</pre><p>Procedures are also a very useful feature of Snowflake where you can utilize Snowflake SQL Scripting, Python, Java, which is super handy.</p><p><strong>The Iterative Merge Framework</strong></p><p>Ideally for a problem like I described you need a way to iterate, and you do that with a FOR LOOP like the example above. However, with my example I don’t use a RESULTSET and I have stripped the code a bit (its a large statement!) so that anyone can use this and modify it as you see fit.</p><p>The merge example I am showing here also has other features and/or columns you may or may not need. Hopefully it will inspire you!</p><p>(basic and expanded frameworks)</p><pre>CREATE OR REPLACE PROCEDURE DATABASE.SCHEMA.ITERATIVE_MERGE_PROCEDURE()<br>RETURNS VARCHAR<br>LANGUAGE SQL<br>AS<br>DECLARE<br>    --Set CURSOR to iterate through all events, ideally ordered by a Unique Row ID and Row Number<br>    --This example is grabbing only a set of data as the Proc will run daily<br>    --The selection is taken from a staged data area<br>    --- (Rename anything where needed)<br>    cur CURSOR FOR<br>    SELECT PKEY_ID, UNIQUE_EVENT_ID, EVENT_DATE, ROW_NUMBER, ROW_TYPE -- &#39;CREATED&#39; or &#39;CHANGED&#39; or &#39;DELETED&#39;<br>    FROM DATABASE.SCHEMA.HISTORICAL_EVENT_STAGE_TBL<br>    WHERE EVENT_DATE BETWEEN CURRENT_DATE()-2 AND CURRENT_DATE() -- Set interval as needed<br>    ORDER BY UNIQUE_EVENT_ID, ROW_NUMBER;<br>    --Define Iteration Variables<br>    v_UNIQUE_EVENT_ID STRING;<br>    v_EVENT_DATE TIMESTAMP;<br>    v_PKEY_ID STRING; --In this example, the stage had a primary key row id<br>    v_ROW_NUMBER NUMBER; --Useful for &#39;CHANGED&#39; rows that share a profile id, the use case derived for this shared &#39;unique_event_id&#39; for the type of actions<br>    v_ROW_TYPE STRING; --Example &#39;CREATED&#39; or &#39;CHANGED&#39; or &#39;DELETED&#39;<br><br>BEGIN<br>    --Start by Opening the Cursor<br>    OPEN cur;<br><br>    --Loop through each row in the cursor<br>    --Ideally if the cursor is small, the iteration is faster<br>    ---For a very large selection, the iteration will be slower<br>    FOR r IN cur DO<br>        --Extract the necessary fields from the current record<br>        --And assign to the variable definitions<br>        v_UNIQUE_EVENT_ID := r.UNIQUE_EVENT_ID;<br>        v_EVENT_DATE := r.EVENT_DATE;<br>        v_PKEY_ID := r.PKEY_ID;<br>        v_ROW_NUMBER := r.ROW_NUMBER;<br>        v_ROW_TYPE := r.ROW_TYPE;<br>        <br>        MERGE INTO DATABASE.SCHEMA.FINAL_TABLE AS target<br>        USING (<br>            -- Filtering on variables of the table with the cursor<br>            SELECT * FROM DATABASE.SCHEMA.HISTORICAL_EVENT_STAGE_TBL<br>            WHERE UNIQUE_EVENT_ID = :v_UNIQUE_EVENT_ID AND PKEY_ID = :v_PKEY_ID AND ROW_NUMBER = :v_ROW_NUMBER<br>            ) AS source<br>        ON <br>            target.UNIQUE_EVENT_ID = source.UNIQUE_EVENT_ID<br>        WHEN MATCHED AND source.ROW_TYPE = &#39;CHANGED&#39; AND target.EVENT_DATE &lt; source.EVENT_DATE THEN<br>            UPDATE SET<br>                --Update actions<br>        WHEN MATCHED AND source.ROW_TYPE = &#39;DELETED&#39; AND target.EVENT_DATE &lt; source.EVENT_DATE THEN<br>            DELETE<br>                --Delete actions<br>        WHEN NOT MATCHED AND source.ROW_TYPE = &#39;CREATED&#39; THEN<br>                --Insert actions<br>            INSERT (target.COLNAME)<br>            VALUES (source.COLNAME);<br>    <br>    END FOR;<br><br>    CLOSE cur;<br>    <br>END;</pre><pre>--Iterative Merge Procedure<br>--Version 1: Created by Luke Haakenson<br>CREATE OR REPLACE PROCEDURE DATABASE.SCHEMA.ITERATIVE_MERGE_PROCEDURE()<br>RETURNS VARCHAR<br>LANGUAGE SQL<br>AS<br>DECLARE<br>    --Set CURSOR to iterate through all events, ideally ordered by a Unique Row ID and Row Number<br>    --This example is grabbing only a set of data as the Proc will run daily<br>    --The selection is taken from a staged data area<br>    --- (Rename anything where needed)<br>    cur CURSOR FOR<br>    SELECT PKEY_ID, UNIQUE_EVENT_ID, EVENT_DATE, ROW_NUMBER, ROW_TYPE -- &#39;CREATED&#39; or &#39;CHANGED&#39;<br>    FROM DATABASE.SCHEMA.HISTORICAL_EVENT_STAGE_TBL<br>    WHERE EVENT_DATE BETWEEN CURRENT_DATE()-2 AND CURRENT_DATE() -- Set interval as needed<br>    ORDER BY UNIQUE_EVENT_ID, ROW_NUMBER;<br>    --Define Iteration Variables<br>    v_UNIQUE_EVENT_ID STRING;<br>    v_EVENT_DATE TIMESTAMP;<br>    v_PKEY_ID STRING; --In this example, the stage had a primary key row id<br>    v_ROW_NUMBER NUMBER;<br>    v_ROW_TYPE STRING; --Example &#39;CREATED&#39; or &#39;CHANGED&#39;<br><br>BEGIN<br>    --Start by Opening the Cursor<br>    OPEN cur;<br><br>    --Loop through each row in the cursor<br>    --Ideally if the cursor is small, the iteration is faster<br>    ---For a very large selection, the iteration will be slower<br>    FOR r IN cur DO<br>        --Extract the necessary fields from the current record<br>        --And assign to the variable definitions<br>        v_UNIQUE_EVENT_ID := r.UNIQUE_EVENT_ID;<br>        v_EVENT_DATE := r.EVENT_DATE;<br>        v_PKEY_ID := r.PKEY_ID;<br>        v_ROW_NUMBER := r.ROW_NUMBER;<br>        v_ROW_TYPE := r.ROW_TYPE;<br>        <br>        MERGE INTO DATABASE.SCHEMA.FINAL_TABLE AS target<br>        USING (<br>            -- Filtering on variables of the table with the cursor<br>            SELECT * FROM DATABASE.SCHEMA.HISTORICAL_EVENT_STAGE_TBL<br>            WHERE UNIQUE_EVENT_ID = :v_UNIQUE_EVENT_ID AND PKEY_ID = :v_PKEY_ID AND ROW_NUMBER = :v_ROW_NUMBER<br>            ) AS source<br>        ON <br>            target.UNIQUE_EVENT_ID = source.UNIQUE_EVENT_ID<br>        WHEN MATCHED AND source.ROW_TYPE = &#39;CHANGED&#39; AND target.EVENT_DATE &lt; source.EVENT_DATE THEN<br>            UPDATE SET<br>                --Fields where you do want to record last previous value if changed<br>                target.PROFILE_ACTIVE_PREVIOUS = CASE WHEN target.PROFILE_ACTIVE != source.PROFILE_ACTIVE THEN target.PROFILE_ACTIVE ELSE target.PROFILE_ACTIVE_PREVIOUS END,<br>                target.PROFILE_ACTIVE = COALESCE(source.PROFILE_ACTIVE, target.PROFILE_ACTIVE),<br>                target.FIRST_NAME_PREVIOUS = CASE WHEN target.FIRST_NAME != source.FIRST_NAME THEN target.FIRST_NAME ELSE target.FIRST_NAME_PREVIOUS END,<br>                target.FIRST_NAME = COALESCE(source.FIRST_NAME, target.FIRST_NAME),<br>                ----add or remove columns as needed<br>                --Fields where you don&#39;t want to record previous value and obtain the latest value if not null<br>                target.MODIFIED_AT = COALESCE(source.MODIFIED_AT, target.MODIFIED_AT),<br>                target.MODIFIED_BY = COALESCE(source.MODIFIED_BY, target.MODIFIED_BY),<br>                target.CREATED_AT = COALESCE(source.CREATED_AT, target.CREATED_AT),<br>                target.CREATED_BY = COALESCE(source.CREATED_BY, target.CREATED_BY),<br>                target.EVENT_DATE = COALESCE(source.EVENT_DATE, target.EVENT_DATE),<br>                target.USER_ID = COALESCE(source.USER_ID, target.USER_ID),<br>                target.USERNAME = COALESCE(source.USERNAME, target.USERNAME),<br>                -----add or remove columns as needed<br>                -- This is used to calculate how many fields were last updated<br>                target.PROFILE_UPDATED = <br>                    CASE <br>                        WHEN (<br>                            target.PROFILE_ACTIVE != source.PROFILE_ACTIVE OR<br>                            target.FIRST_NAME != source.FIRST_NAME<br>                            --When not equal start count<br>                            --Add or remove as needed<br>                        ) THEN <br>                            CONCAT(<br>                                CAST(<br>                                    (   CASE WHEN target.PROFILE_ACTIVE != source.PROFILE_ACTIVE THEN 1 ELSE 0 END +<br>                                        CASE WHEN target.FIRST_NAME != source.FIRST_NAME THEN 1 ELSE 0 END<br>                                        --Add or remove as needed <br>                                    ) AS STRING<br>                                ), &#39; Fields Updated&#39;<br>                            )<br>                        ELSE &#39;0 Fields Updated&#39;<br>                    END,<br>                target.PKEY_ID_OF_CHANGE_ROW = source.PKEY_ID<br>        <br>            WHEN NOT MATCHED AND source.ROW_TYPE = &#39;CREATED&#39; THEN<br>                INSERT (--All Target Table Columns, Add or remove as needed<br>                        target.PKEY_ID, <br>                        target.PROFILE_ACTIVE, <br>                        target.PROFILE_ACTIVE_PREVIOUS, <br>                        target.UNIQUE_EVENT_ID,<br>                        target.FIRST_NAME,<br>                        target.FIRST_NAME_PREVIOUS,<br>                        target.MODIFIED_AT,<br>                        target.MODIFIED_BY,<br>                        target.CREATED_AT,<br>                        target.CREATED_BY,<br>                        target.EVENT_DATE,<br>                        target.USER_ID,<br>                        target.USERNAME,<br>                        target.PROFILE_UPDATED,<br>                        target.PKEY_OF_CHANGE_ROW)<br>            VALUES (--Add or remove as needed, keep in mind this example, <br>                    --the originating table does not have previous columns <br>                    --for the &#39;CREATED&#39; event or the derived columns<br>                    --so nulls are used to have same number of columns<br>                        source.PKEY_ID,<br>                        source.PROFILE_ACTIVE,<br>                        null,<br>                        source.UNIQUE_EVENT_ID,<br>                        source.FIRST_NAME,<br>                        null,<br>                        source.MODIFIED_AT,<br>                        source.MODIFIED_BY,<br>                        source.CREATED_AT,<br>                        source.CREATED_BY,<br>                        source.EVENT_DATE,<br>                        source.USER_ID,<br>                        source.USERNAME,<br>                        null,<br>                       &#39;New Row&#39; --Initial &#39;CREATED&#39; may not have &#39;CHANGED&#39;<br>            );<br>    <br>    END FOR;<br><br>    CLOSE cur;<br><br>    --RETURN CODE<br>    IF (SQLFOUND = true) THEN<br>    RETURN &#39;Updated &#39; || SQLROWCOUNT || &#39; rows.&#39;;<br>  -- SQLNOTFOUND returns &#39;true&#39; if the last DML statement<br>  -- (the UPDATE statement) affected zero rows.<br>  ELSEIF (SQLNOTFOUND = true) THEN<br>    RETURN &#39;No rows updated.&#39;;<br>  ELSE<br>    RETURN &#39;SQLFOUND and SQLNOTFOUND are not true.&#39;;<br>  END IF;<br>    <br>END;</pre><ol><li>If there are multiple ‘CHANGED’ that are captured from the Staged data, it will iterate and perform the Merge in order of the operations from the least Timestamp to the greatest.</li><li>If you need a way to record what the previous value was, especially if your ‘CHANGED’ data includes it, this shows an example of how you might include it for the final table.</li><li>A counter is included that will count the number of changes that occurred, ideally these will be any data point that can be modified and recorded in a change capture. This only counts any changes of the LAST ‘CHANGED’ event that the Merge iterates through.</li><li>The derived row PKEY_ID_OF_CHANGE_ROW is a way to include the row of LAST ‘CHANGED’ event. For this example, the actual setup that we are using the stage includes all historical ‘CREATED’ and ‘CHANGED’ so one can go back and look at all the events that were captured. This could modified further, for example, to make it into an Array and append each unique id of the row if you wanted to (rather than overwrite as multiple changes occur back to back or over time).</li></ol><p>If you wish to connect you can find me over on <a href="https://www.linkedin.com/in/luke-haakenson/">Linkedin</a>, enjoy!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=128a1bc34f1f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>