Skip to content

Commit 6ae4b49

Browse files
committed
Fix(tsql): do not bubble up CTEs in TVF DDLs with inline RETURN queries closes #7721
1 parent 6ecc678 commit 6ae4b49

2 files changed

Lines changed: 12 additions & 0 deletions

File tree

sqlglot/generators/tsql.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -417,6 +417,15 @@ def create_sql(self, expression: exp.Create) -> str:
417417
# but CREATE VIEW actually requires the WITH clause to come after it so we need
418418
# to amend the AST by moving the CTEs to the CREATE VIEW statement's query.
419419
ctas_expression.set("with_", with_.pop())
420+
elif (
421+
kind == "FUNCTION"
422+
and isinstance(ctas_expression, exp.Return)
423+
and isinstance(body := ctas_expression.this.unnest(), exp.Query)
424+
and (with_ := expression.args.get("with_"))
425+
):
426+
# Similar to the VIEW branch, the table-valued functions require the WITH clause
427+
# to stay inside the RETURN body, so we move back any CTEs that were bubbled up.
428+
body.set("with_", with_.pop())
420429

421430
table = expression.find(exp.Table)
422431

tests/dialects/test_tsql.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1374,6 +1374,9 @@ def test_udf(self):
13741374

13751375
self.validate_identity("CREATE FUNCTION foo(@bar INTEGER) RETURNS TABLE AS RETURN SELECT 1")
13761376
self.validate_identity("CREATE FUNCTION dbo.ISOweek(@DATE DATETIME2) RETURNS INTEGER")
1377+
self.validate_identity(
1378+
"CREATE FUNCTION dbo.f() RETURNS TABLE AS RETURN (WITH subquery AS (SELECT id AS id FROM subtable) SELECT other_id FROM main_table AS mt INNER JOIN subquery ON subquery.id = mt.other_id)"
1379+
)
13771380

13781381
# The following two cases don't necessarily correspond to valid TSQL, but they are used to verify
13791382
# that the syntax RETURNS @return_variable TABLE <table_type_definition> ... is parsed correctly.

0 commit comments

Comments
 (0)