Skip to content

Commit c25a9ab

Browse files
authored
Fix(tsql): Keep CTE's attached to the query when emulating IF NOT EXISTS (#4279)
1 parent 2b4229c commit c25a9ab

File tree

2 files changed

+11
-4
lines changed

2 files changed

+11
-4
lines changed

sqlglot/dialects/tsql.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1103,20 +1103,21 @@ def create_sql(self, expression: exp.Create) -> str:
11031103

11041104
if exists:
11051105
identifier = self.sql(exp.Literal.string(exp.table_name(table) if table else ""))
1106-
sql = self.sql(exp.Literal.string(sql))
1106+
sql_with_ctes = self.prepend_ctes(expression, sql)
1107+
sql_literal = self.sql(exp.Literal.string(sql_with_ctes))
11071108
if kind == "SCHEMA":
1108-
sql = f"""IF NOT EXISTS (SELECT * FROM information_schema.schemata WHERE schema_name = {identifier}) EXEC({sql})"""
1109+
return f"""IF NOT EXISTS (SELECT * FROM information_schema.schemata WHERE schema_name = {identifier}) EXEC({sql_literal})"""
11091110
elif kind == "TABLE":
11101111
assert table
11111112
where = exp.and_(
11121113
exp.column("table_name").eq(table.name),
11131114
exp.column("table_schema").eq(table.db) if table.db else None,
11141115
exp.column("table_catalog").eq(table.catalog) if table.catalog else None,
11151116
)
1116-
sql = f"""IF NOT EXISTS (SELECT * FROM information_schema.tables WHERE {where}) EXEC({sql})"""
1117+
return f"""IF NOT EXISTS (SELECT * FROM information_schema.tables WHERE {where}) EXEC({sql_literal})"""
11171118
elif kind == "INDEX":
11181119
index = self.sql(exp.Literal.string(expression.this.text("this")))
1119-
sql = f"""IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = object_id({identifier}) AND name = {index}) EXEC({sql})"""
1120+
return f"""IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = object_id({identifier}) AND name = {index}) EXEC({sql_literal})"""
11201121
elif expression.args.get("replace"):
11211122
sql = sql.replace("CREATE OR REPLACE ", "CREATE OR ALTER ", 1)
11221123

tests/dialects/test_tsql.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -920,6 +920,12 @@ def test_ddl(self):
920920
"": "CREATE TABLE IF NOT EXISTS foo.bar.baz AS SELECT '2020' AS z FROM a.b.c",
921921
},
922922
)
923+
self.validate_all(
924+
"IF NOT EXISTS (SELECT * FROM information_schema.tables WHERE table_name = 'baz' AND table_schema = 'bar' AND table_catalog = 'foo') EXEC('WITH cte1 AS (SELECT 1 AS col_a), cte2 AS (SELECT 1 AS col_b) SELECT * INTO foo.bar.baz FROM (SELECT col_a FROM cte1 UNION ALL SELECT col_b FROM cte2) AS temp')",
925+
read={
926+
"": "CREATE TABLE IF NOT EXISTS foo.bar.baz AS WITH cte1 AS (SELECT 1 AS col_a), cte2 AS (SELECT 1 AS col_b) SELECT col_a FROM cte1 UNION ALL SELECT col_b FROM cte2"
927+
},
928+
)
923929
self.validate_all(
924930
"CREATE OR ALTER VIEW a.b AS SELECT 1",
925931
read={

0 commit comments

Comments
 (0)