Running a macro using dbt and getting incorrect results.
I am running the below macro:
{% set value = 0 %}
{% for key , v in metrics.items() %}
{% if col in v %}
{% set value = value + 1 %}
{{value}}
{{key}}({%- if relation_alias %}{{ relation_alias }}.{{ col|trim }}){%- endi -%}
{% endif %}
{% endfor %}
{{ value }}
I am getting the value as 0 outside the for loop even after the if condition is met. I am expecting value as 1 after for loop is executed. Kindly suggest.
You need to put your variable into a namespace in order for it to be updated in the loop:
{% set ns = namespace(value = 0) %}
{% for key , v in metrics.items() %}
{% if col in v %}
{% set ns.value = ns.value + 1 %}
{{value}}
{{key}}({%- if relation_alias %}{{ relation_alias }}.{{ col|trim }}){%- endif -%}
{% endif %}
{% endfor %}
{{ ns.value }}