apache / datafusion-sqlparser-rs

Extensible SQL Lexer and Parser for Rust
Apache License 2.0
2.8k stars 543 forks source link

MSSQL: Issue with CTE anchors #1537

Open kasvith opened 2 days ago

kasvith commented 2 days ago

Hi, the following is a valid MSSQL syntax

When parsed with the sql-parser-rs

WITH RecursiveCTE AS (
    -- Anchor member
    SELECT TOP 1
        [ID],
        CAST([Amount] AS NUMERIC) AS [Amount],
        CAST([Balance] AS NUMERIC) AS [Balance],
        (SELECT TOP 1 [FixedValue] FROM [Settings] ORDER BY [ID] DESC) AS [Constant]
    FROM [Transactions]
    ORDER BY [ID] ASC

    UNION ALL

    -- Recursive member
    SELECT
        [ID] + 1 AS [ID],
        CAST([Amount] * 0.8 AS NUMERIC) AS [Amount],
        CAST(([Amount] * 0.8 - [Constant]) AS NUMERIC) AS [Balance],
        [Constant]
    FROM RecursiveCTE
    WHERE [Balance] > 0
)
SELECT [ID], [Balance]
FROM RecursiveCTE
ORDER BY [ID] ASC;

it gives the following error

sql parser error: Expected: ), found: UNION at Line: 11, Column: 5

https://learn.microsoft.com/en-us/sql/t-sql/queries/with-common-table-expression-transact-sql