Ambiguous column name error, how do I fix it? Ambiguous column name error, how do I fix it? sql sql

Ambiguous column name error, how do I fix it?


You need to add the alias for the Groups table. Change this:

UPDATE dbo.GroupsSET Flags = @varFROM dbo.Users u INNER JOIN dbo.UsersGroups ug ON u.UserID = ug.UserIDINNER JOIN dbo.Groups g ON g.GroupID = ug.GroupIDWHERE u.UserName = 'UserA'

To this:

UPDATE g -- change dbo.Groups here to simply 'g'SET g.Flags = @varFROM dbo.Users u INNER JOIN dbo.UsersGroups ug ON u.UserID = ug.UserIDINNER JOIN dbo.Groups g ON g.GroupID = ug.GroupIDWHERE u.UserName = 'UserA'


The problem is that you haven't specified the table name for the field "Flags" and it probably exists in more than one table in the query. Add the table name in the format "Tablename.flags" to the front of all references to fix the problem.


UPDATE gSET g.Flags = @varFROM  dbo.Groups g    INNER JOIN  dbo.UsersGroups ug    ON g.GroupID = ug.GroupID    INNER JOIN  dbo.Users u    ON u.UserID = ug.UserIDWHERE u.UserName = 'UserA'
  • In the from clause - the update target needs to be the first table there.
  • In the update clause - use the table alias created in the from clause.
  • In the set clause - use the table alias created in the from clause.

I once knew the reasons that this dance needs to be done this way - now I just do it out of habit. I suspect it has something to do with TSQL's double FROM clause in DELETE statements, and the possibility of talking about Two different instances of the Groups table between the FROM and UPDATE clause... or even Two different instances of the Groups table in the from clause (think self-join).