SQL Server 从一个表到ID匹配的另一个表的SQL更新

wtlkbnrh  于 2022-12-10  发布在  其他
关注(0)|答案(3)|浏览(149)

I have 2 databases Alpha and Beta. Each database has identical table "Comments". The Comments table has 2 fields: ID and Comments. Alpha.Comments has only ID field populated, corresponding Comment field is empty. Beta.Comments has both ID and the corresponding comments. Is there SQL Query that can update all of Alpha.Comments field with appropriate entries from Beta, where ID matches?

lp0sw83n

lp0sw83n2#

Something like:

update alpha.comments
    set comments = (select b.comments from beta.comments b where b.id = comments.id);

In SQL Server, you can can express this as:

update a
    set comments = b.comments
    from alpha.comments a join
         beta.comments b
         on a.id = b.id;

This handles duplicates in an unfortunate way. It arbitrarily chooses one for the assignment, so no error is generated.

nbysray5

nbysray53#

可以这样更新

UPDATE Alpha SET Comments=(
SELECT Comments
FROM Beta
WHERE Beta.ID = Alpha.ID
);

相关问题