From a647364c4c7cb063063e73301f16bc1a5e84f170 Mon Sep 17 00:00:00 2001 From: Lucas Ortiz Date: Mon, 21 Aug 2023 11:03:26 +0200 Subject: [PATCH] add dbt_utils/sqlserver__generate_surrogate_key macro to fix concat bug #97 --- .../dbt_utils/sql/generate_surrogate_key.sql | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 macros/dbt_utils/sql/generate_surrogate_key.sql diff --git a/macros/dbt_utils/sql/generate_surrogate_key.sql b/macros/dbt_utils/sql/generate_surrogate_key.sql new file mode 100644 index 0000000..da31f58 --- /dev/null +++ b/macros/dbt_utils/sql/generate_surrogate_key.sql @@ -0,0 +1,29 @@ +{%- macro sqlserver__generate_surrogate_key(field_list) -%} + +{%- if var('surrogate_key_treat_nulls_as_empty_strings', False) -%} + {%- set default_null_value = "" -%} +{%- else -%} + {%- set default_null_value = '_dbt_utils_surrogate_key_null_' -%} +{%- endif -%} + +{%- set fields = [] -%} + +{%- for field in field_list -%} + + {%- do fields.append( + "coalesce(cast(" ~ field ~ " as " ~ dbt.type_string() ~ "), '" ~ default_null_value ~"')" + ) -%} + + {%- if not loop.last %} + {%- do fields.append("'-'") -%} + {%- endif -%} + +{%- endfor -%} + +{%- if fields|length > 1 %} + {{ dbt.hash(dbt.concat(fields)) }} +{%- else -%} + {{ dbt.hash(fields[0]) }} +{%- endif -%} + +{%- endmacro -%}