sqlglot icon indicating copy to clipboard operation
sqlglot copied to clipboard

tsql: block-closing END gets absorbed as an implicit column alias

Open princejain756 opened this issue 1 month ago • 1 comments

Describe the bug In T-SQL, END is reserved for closing BEGIN ... END blocks and CASE expressions, so it cannot be an implicit column alias. sqlglot's T-SQL parser still treats it as one, which silently corrupts IF ... BEGIN ... END blocks: the terminating END gets absorbed into the last statement as an alias and the block never closes.

To Reproduce

import sqlglot

sqlglot.parse_one("IF (@a = 1) BEGIN SELECT 1 END", read="tsql").sql("tsql")
# 'IF @a = 1 BEGIN SELECT 1 AS END'
# expected: the END closes the block, SELECT 1 has no alias

sqlglot.parse_one("IF (@a = 1) BEGIN SELECT 1 AS x END", read="tsql").sql("tsql")
# 'IF @a = 1 BEGIN SELECT 1 AS x AS END'

sqlglot.parse_one("IF (@a = 1) BEGIN SELECT 1; SELECT 2 END", read="tsql").sql("tsql")
# 'IF @a = 1 BEGIN SELECT 1; SELECT 2 AS END'

Expected behavior END closes the block. The statements above should emit IF @a = 1 BEGIN SELECT 1; END, ... SELECT 1 AS x; END, ... SELECT 1; SELECT 2; END, and IF (@a = 1) BEGIN SELECT 1 END ELSE BEGIN SELECT 2 END should keep its else branch.

Fix A working fix is on my fork, branch fix-tsql-end-alias: excludes END from TSQLParser's alias token sets (mirroring the existing BEGIN exclusion) and lets the batch-statement loop treat a trailing END inside a chunk (or one followed by ELSE) as the block terminator. Full test suite passes (1404 tests, 21896 subtests), including all existing CASE ... END coverage.

princejain756 avatar Oct 22 '26 13:10 princejain756

Thanks, but this is low priority for the core team.

georgesittas avatar Oct 22 '26 13:10 georgesittas