From 3cdf83f88ae39d3f3e84f04f3704f72eae7566d1 Mon Sep 17 00:00:00 2001 From: silviu stanimir Date: Wed, 15 Nov 2023 17:15:11 +0100 Subject: [PATCH] feat: implement charindex macro --- README.md | 7 +++++++ macros/multiple_databases/charindex.sql | 21 +++++++++++++++++++++ 2 files changed, 28 insertions(+) create mode 100644 macros/multiple_databases/charindex.sql diff --git a/README.md b/README.md index 7d55768..055dd25 100644 --- a/README.md +++ b/README.md @@ -26,6 +26,7 @@ This dbt package contains macros for SQL functions to run the dbt project on mul - [Multiple databases](#Multiple-databases) - [as_varchar](#as_varchar-source) + - [charindex](#charindex-source) - [create_index](#create_index-source) - [date_from_timestamp](#date_from_timestamp-source) - [datediff](#datediff-source) @@ -61,6 +62,12 @@ This macro converts a string to the data type `nvarchar(2000)` for SQL Server. U Usage: `{{ pm_utils.as_varchar('[expression]') }}` +#### charindex ([source](macros/multiple_databases/charindex.sql)) +This macro returns the starting position of the first occurrence of a string in another string. The search is not case-sensitive. If the string is not found, the function returns 0. This macro can be used to check whether a string contains another string. + +Usage: +`{{ pm_utils.charindex('[expression_to_find]', '[field]', '[start_location]') }}` + #### create_index ([source](macros/multiple_databases/create_index.sql)) This macro creates a clustered columnstore index on the current model for SQL Server. This macro should be used in a dbt post-hook. diff --git a/macros/multiple_databases/charindex.sql b/macros/multiple_databases/charindex.sql new file mode 100644 index 0000000..66a4e83 --- /dev/null +++ b/macros/multiple_databases/charindex.sql @@ -0,0 +1,21 @@ +{%- macro charindex(expression_to_find, field, start_location=None) -%} +case + when len('{{ expression_to_find }}') > 0 + then + {% if start_location is none -%} + {% if target.type == 'databricks' -%} + position('{{ expression_to_find }}', {{ field }}) + {% else -%} + charindex('{{ expression_to_find }}', {{ field }}) + {% endif -%} + {% else -%} + {% if target.type == 'databricks' -%} + position('{{ expression_to_find }}', {{ field }}, {{ start_location }}) + {% else -%} + charindex('{{ expression_to_find }}', {{ field }}, {{ start_location }}) + {% endif -%} + {% endif -%} + else + 0 +end +{%- endmacro -%}