Search code examples
sql-serverjoinmultipart

Multipart identifier column not bound in SQL


Please can you help. I am trying to do something as below:

Select tb4.columnName As test1,
   tb2.columnName As test2,
   tb4.columnName As test3 
from [dbname].Table2 tb2, Table1  tb1 
JOIN Table3 tb3 ON tb3.ColumnName = tb1.columnName 
JOIN Table4 tb4 ON tb4.ColumnName = tb3.columnName
JOIN [dbname].Table5 tb5 ON tb5.ColumnName = **tb2.ColumnName**

I am getting:

multipart identifier not bound error at ‘tb2.ColumnName’


Solution

  • Never mix implicit joins (with commas in the from clause) and explicit joins (with the join ... on syntax). They have different prescendence, so at the time when the last join condition is evaluated, the database does not know about tb2 yet.

    Matter of fact, always use explicit joins: they have been the standard for decades now. Your existing query is seemingly missing a join condition between tb2 and tb1, but the logic you want should be:

    select 
        tb4.columnName As test1,
        tb2.columnName As test2,
        tb4.columnName As test3 
    from Table2 tb2
    inner join Table1 tb1 on ??  -- join condition here
    inner join Table3 tb3 on tb3.ColumnName = tb1.columnName 
    inner join Table4 tb4 on tb4.ColumnName = tb3.columnName
    inner join Table5 tb5 on tb5.ColumnName = tb2.ColumnName