TaoK/PoorMansTSqlFormatter — Issue #30: Incorrect formatting on nested joins, esp. without parens
Author: TaoK
Created: 2011-12-06 21:34:16+00:00
State: open
Labels: priority-medium

The following "nested join" syntax is parsed incorrectly. The resulting formatted SQL is still 100% correct and equivalent, but the formatting is not correct:

```
DECLARE @TestTable TABLE (TestColumn1 Int, TestColumn2 Int)
INSERT INTO @TestTable VALUES (1, 1), (1, 2), (2, 2)

SELECT [1].*, [2].*
FROM @TestTable [1]
LEFT JOIN @TestTable [2]
INNER JOIN @TestTable [3] ON [2].TestColumn2 = [3].TestColumn2
AND 1 < 2
ON [1].TestColumn1 = [2].TestColumn1
```

When you add parens the meaning becomes slightly clearer, but the formatting is even more whacky, with the inner join going undetected:

```
DECLARE @TestTable TABLE (TestColumn1 Int, TestColumn2 Int)
INSERT INTO @TestTable VALUES (1, 1), (1, 2), (2, 2)

SELECT [1].*, [2].*
FROM @TestTable [1]
LEFT JOIN (@TestTable [2]
INNER JOIN @TestTable [3] ON [2].TestColumn2 = [3].TestColumn2
AND 1 < 2)
ON [1].TestColumn1 = [2].TestColumn1
```

---

Original example from Hugo [Kornelis' QOTD](http://www.sqlservercentral.com/questions/T-SQL/77296/), possibly for test suite:

```
SELECT e.Name AS SalesRep, c.Name AS Customer, o.OrderDate
FROM dbo.Employees AS e
LEFT JOIN dbo.Customers AS c
INNER JOIN dbo.Orders AS o
ON o.CustomerID = c.CustomerID
AND o.OrderDate > DATEADD(month, -4, CURRENT_TIMESTAMP)
ON c.SalesRep = e.EmployeeID
WHERE e.Position = 'SalesRep';
```