sql – 如何使用连接检索的数据更新表本身?

前端之家收集整理的这篇文章主要介绍了sql – 如何使用连接检索的数据更新表本身?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下数据:
SectorKey Sector foo  
1         A      null 
2         B      null
...       ...    ...
1         null   a  
2         null   b 
2         null   c 
1         null   d 
2         null   e 
...       ...    ...

我希望根据sectorKey的值更新列为Sector时的扇区,即当SectorKey为1时我希望Sector为’A’,而当SectorKey为2时我想要’B’

我试过这个查询

update tbFoo
set Sector=A.sector 
from tbFoo A INNER JOIN tbFoo B
ON A.SectorKey=B.SectorKey 
and A.Sector is not null 
and B.Sector is null

并收到此错误消息:

The table ‘tbFoo’ is ambiguous.

我试过别名第一个tbFoo,但它似乎不是一个有效的语法.我不明白为什么sqlServer抱怨模糊的命名,因为我的所有表都有别名.

我找到了this thread,而且我觉得我做的事与在upvoted答案中完全一样.我也尝试了在接受的答案中建议的查询

update tbFoo A
    set Sector = 
       (select Sector from tbFoo 
        where A.SectorKey=SectorKey and Sector is not null)

然后sqlServer抱怨“A”附近的语法不正确

关于可能发生的事情的任何想法,并解决这个问题?我正在使用sqlServer 2008.

编辑我没有显示我的表的总数据.我不只有两个案例(A和B),而是几千个案例.所以一个明确的案例不是一个选择

解决方法

使用更新查询第一部分中的别名:
update B
set Sector=A.sector 
from tbFoo A INNER JOIN tbFoo B
ON A.SectorKey=B.SectorKey 
and A.Sector is not null 
and B.Sector is null

否则,它不知道要更新的表的哪个实例.

原文链接:https://www.f2er.com/mssql/77919.html

猜你在找的MsSQL相关文章