加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

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

发布时间:2020-12-12 06:46:28 所属栏目:MsSql教程 来源:网络整理
导读:我有以下数据: 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’ 我试
我有以下数据:
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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读