Skip to content

Commit 489154e

Browse files
committed
drop referenced views
1 parent 0b0ba9c commit 489154e

File tree

1 file changed

+24
-11
lines changed

1 file changed

+24
-11
lines changed

dbt/include/sqlserver/macros/adapters/relation.sql

Lines changed: 24 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -13,17 +13,30 @@
1313
{% endmacro %}
1414

1515
{% macro sqlserver__drop_relation_script(relation) -%}
16-
{% if relation.type == 'view' -%}
17-
{% set object_id_type = 'V' %}
18-
{% elif relation.type == 'table'%}
19-
{% set object_id_type = 'U' %}
20-
{%- else -%} invalid target name
21-
{% endif %}
22-
USE [{{ relation.database }}];
23-
if object_id ('{{ relation.include(database=False) }}','{{ object_id_type }}') is not null
24-
begin
25-
drop {{ relation.type }} {{ relation.include(database=False) }}
26-
end
16+
{% call statement('find_references', fetch_result=true) %}
17+
USE [{{ relation.database }}];
18+
SELECT referencing_schema_name, referencing_entity_name
19+
FROM sys.dm_sql_referencing_entities ('{{ relation.include(database=false) }}', 'object')
20+
{% endcall %}
21+
{% set references = load_result('find_references')['data'] %}
22+
{% for reference in references -%}
23+
-- dropping referenced view {{ reference[0] }}.{{ reference[1] }}
24+
{{ sqlserver__drop_relation_script(relation.incorporate(
25+
type="view",
26+
path={"schema": reference[0], "identifier": reference[1]})) }}
27+
{% endfor %}
28+
{% if relation.type == 'view' -%}
29+
{% set object_id_type = 'V' %}
30+
{% elif relation.type == 'table'%}
31+
{% set object_id_type = 'U' %}
32+
{%- else -%}
33+
{{ exceptions.raise_not_implemented('Invalid relation being dropped: ' ~ relation) }}
34+
{% endif %}
35+
USE [{{ relation.database }}];
36+
if object_id ('{{ relation.include(database=False) }}','{{ object_id_type }}') is not null
37+
begin
38+
drop {{ relation.type }} {{ relation.include(database=False) }}
39+
end
2740
{% endmacro %}
2841

2942
{% macro sqlserver__rename_relation(from_relation, to_relation) -%}

0 commit comments

Comments
 (0)