Update SQL with Aliased tables still returns “table is ambiguous” error

筅森魡賤 提交于 2020-12-31 04:38:36

问题


I am trying to run the below update but running into the "table is ambiguous" error.

UPDATE dbo.cg
SET cg.column = gId.ID
FROM    dbo.a
        INNER JOIN dbo.cg as cId ON cId.[a] = dbo.a.[c]
        INNER JOIN dbo.cg as gId ON gId.[a] = dbo.a.[b];

The table dbo.a contains data to update a value in cg based on a relationship to same table against a value in a different column. It is a self-referencing hierarchy.

As you can see, everything is aliased so I am a bit confused why this won't run.

Many thanks in advance for any help that can be provided.


回答1:


In SQL Server, you should use the alias in the update, not the table. In addition, you have no alias called cg. So something like this:

UPDATE cId
SET column = gId.ID
FROM dbo.a a INNER JOIN
     dbo.cg cId
     ON cId.[a] = a.[c] INNER JOIN
     dbo.cg gId
     ON gId.[a] = a.[b];



回答2:


Not to worry, solved it by luck.

I inner joined the table to itself in desperation ...

UPDATE dbo.cg
SET cg.column = gId.ID
FROM    dbo.a
        INNER JOIN dbo.cg as cId ON cId.[a] = dbo.a.[c]
        INNER JOIN dbo.cg as gId ON gId.[a] = dbo.a.[b]
        INNER JOIN cg ON cId.[a] = cg.[a];

If anyone could explain why that has worked, I would really appreciate understanding the MS SQL logic underneath.



来源:https://stackoverflow.com/questions/34271322/update-sql-with-aliased-tables-still-returns-table-is-ambiguous-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!