简体   繁体   English

合并以更新所有目标表列

[英]Merge to update all target table columns

I have the same table in 2 Databases 我在2个数据库中有相同的表

-----------------------------------
|           table                 |
-----------------------------------
| ID | col1 | col2 | ... | col(n) |

I need merge statement to update rows with matched IDs like this statement: 我需要merge语句来更新具有匹配ID的行,例如:

MERGE [DB1]..[table]
USING [DB2]..[table] ON [DB1]..[table].[ID] = [DB2]..[table].[ID]
WHEN MATCHED THEN
    UPDATE SET [DB1]..[table].[*] = [DB1]..[table].[*]

the problem is I have more than 30 columns so its difficult to set values column by column . 问题是我有30多个列,因此很难逐列设置值。

There is no way to use a wildcard to specify the target update columns and mappings (even if all columns are identical). 无法使用通配符来指定目标更新列和映射(即使所有列都相同)。 You can get a head start on all the typing by clicking on the Columns node in Object Explorer, and dragging it (and hence the column names) onto your query window: 您可以通过单击“对象资源管理器”中的“ Columns节点,然后将其(并因此将列名称)拖到查询窗口中来开始所有键入操作:

在此处输入图片说明

在此处输入图片说明

So now you don't have all that much typing to do, just a bunch of manipulation and copying and pasting. 因此,现在您无需进行太多键入操作,只需一堆操作以及复制和粘贴即可。

And I wouldn't use MERGE for this anyway, for various reasons (including the fact that the syntax is rather cumbersome when only an UPDATE is involved), and as mentioned in my comment above. 而且出于各种原因(包括仅涉及UPDATE时语法相当繁琐的事实),我也不会为此使用MERGE ,正如我在上面的评论中提到的那样。 See this post for details . 有关详细信息,请参见此帖子

UPDATE trg
  SET col1 = src.col1,
      col2 = src.col2, 
      ...
  FROM DB1.dbo.table AS trg
  INNER JOIN DB2.dbo.table AS src
    ON trg.ID = src.ID;

I think @AaronBertrand is right for this question. 我认为@AaronBertrand对这个问题是正确的。 MERGE Statement is not required. 不需要MERGE语句。 You can just write simple update statement(with join if necessary). 您可以只编写简单的更新语句(必要时使用join)。

1) Simple update 1)简单更新

       UPDATE TableName
          SET col1 ='what you want to update'

2) Two or multiple Updates 2)两个或多个更新

  UPDATE t2
    SET t2.col2 =t.col2,
       t2.col3 =t1.col3,
       t2.col4 =t.col5

    FROM Table t 
    INNER JOIN Table1 t1 on t1.col1=t.col1 
    INNER JOIN Table2 t2 on t2.col1=t1.col1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM