I like to share with you something I managed to make for Amazon Redshift which is dynamic merge statement for SCD(Slowly Changing Dimension) Type 2.
What this statement assumes exist beforehand:
- Two schemas in database - dbimports and repo. dbimports schema is used as staging area and repo will be the target for SCD type 2 dimensions and facts.
- That tables in repo and dbimports schema have the same names along with same column names coming from source data.
- Tables in repo schema will have preset primary keys.
- Tables in repo schema will have three additional columns - scd_key,is_active,inserted_date . scd_key is identity column and can be omitted if the primary key constraint is not enforced.
Note that intentionally I did not add end_date column as I found it not usable in my specific project's case.
What this statement does:
- Create a stored procedure in repo schema with one parameter (table_name varchar(256)).
- Dynamically obtains the table name you want to merge into from table_name parameter and performs UPDATE statement on is_active flag column (set to 0) on matching rows between dbimports table and its mirror table in repo schema.
- Dynamically defines join conditions for the UPDATE statement.
- Makes a INSERT * INTO from dbimports to repo schema with is_active flag set to 1 and current date (GETDATE()).
I know this is not a hard task if you build it in a normal SQL environment, but as you may know, Redshift's SQL is "highly modified". This means that most of normal SQL's features are cut out like variables and triggers, which makes this task pretty hard to figure out (at least for me it was).
Hope this helps anybody. Have a good one.