在 SQL 中,添加一组对应于连接的值

发布于 2024-11-09 03:56:31 字数 532 浏览 0 评论 0原文

假设我有 Table_A 包含:

ID OldValue
3     16
1     5

Table_B 包含

ID Value OldValue
1    2     NULL
2    4     NULL 
3    8     NULL

,并且我想将 Table_A 中的 OldValues 插入到 Table_B 中,其中 ID 相等,结果为:

更新的 Table_B

ID Value OldValue
1    2     5
2    4     NULL 
3    8     16

的方法可以在不使用光标的情况下执行此操作?在现实生活中,这将发生在非常大的表和游标上,众所周知,速度很慢。也许某种合并?

我使用的是 SQL Server 2008

Let's say that I have Table_A contain:

ID OldValue
3     16
1     5

and Table_B contains

ID Value OldValue
1    2     NULL
2    4     NULL 
3    8     NULL

and that I want to insert OldValues from Table_A into Table_B where the IDs equal resulting in :

updated Table_B

ID Value OldValue
1    2     5
2    4     NULL 
3    8     16

Is there a set based way of doing this without using a cursor? In real life this will be going on very large tables and cursors, as we all know are slow. Perhaps some sort of Merge?

I'm on SQL Server 2008

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

自由如风 2024-11-16 03:56:31
Update Table_B
Set OldValue = A.OldValue
From Table_A As A
    Join Table_B As B
        On B.ID = A.ID
Update Table_B
Set OldValue = A.OldValue
From Table_A As A
    Join Table_B As B
        On B.ID = A.ID
孤寂小茶 2024-11-16 03:56:31

你想要一个“更新”

UPDATE B
SET B.OldValue = A.OldValue
FROM Table_B B
INNER JOIN Table_A  ON B.ID = A.ID

通常我把它写成一个选择,然后一旦我得到结果,我就把它转换为更新。

You want an "update from"

UPDATE B
SET B.OldValue = A.OldValue
FROM Table_B B
INNER JOIN Table_A  ON B.ID = A.ID

Generally I write this as a select, then once i get the result I convert it over to the update.

心奴独伤 2024-11-16 03:56:31

简单的:

update x set OldValue = a.OldValue
from Table_B x
join Table_A a on x.ID = a.ID

Simple:

update x set OldValue = a.OldValue
from Table_B x
join Table_A a on x.ID = a.ID
沙与沫 2024-11-16 03:56:31

使用连接:

UPDATE TABLE_B
SET OLDAVLUE=A.OLDVALUE
FROM TABLE_B B 
LEFT JOIN TABLE_A A ON B.ID=A.ID

Use a join:

UPDATE TABLE_B
SET OLDAVLUE=A.OLDVALUE
FROM TABLE_B B 
LEFT JOIN TABLE_A A ON B.ID=A.ID
指尖上得阳光 2024-11-16 03:56:31

也许某种合并?

的确。以下是 SQL Server 2008 支持的标准 SQL:

MERGE INTO Table_B
   USING Table_A
      ON Table_B.ID = Table_A.ID
WHEN MATCHED THEN
   UPDATE
      SET OldValue = Table_A.OldValue;

Perhaps some sort of Merge?

Indeed. The following is Standard SQL that is supported on SQL Server 2008:

MERGE INTO Table_B
   USING Table_A
      ON Table_B.ID = Table_A.ID
WHEN MATCHED THEN
   UPDATE
      SET OldValue = Table_A.OldValue;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文