简体   繁体   English

使用MERGE INTO合并来自不同数据库的2个表

[英]Merging 2 tables from different databases using MERGE INTO

I would like to use MERGE to merge 2 tables from different databases into one table. 我想使用MERGE将来自不同数据库的2个表合并到一个表中。 Both Databases are on the same server. 两个数据库都在同一台服务器上。

Currently, I can do the following: 目前,我可以执行以下操作:

USE Northwind2

SELECT a.CategoryID 
FROM Northwind.dbo.Categories a 
INNER JOIN Northwind2.dbo.Categories b ON a.CategoryID = b.CategoryID

However, I need to merge the results into one table. 但是,我需要将结果合并到一张表中。 I thought I could do something like this: 我以为我可以做这样的事情:

USE Northwind2

MERGE INTO Categories B
USING (
  SELECT E.CategoryID
  FROM Northwind.dbo.Categories) E
ON (B.CategoryID = E.CategoryID)
WHEN MATCHED THEN
  //update the table
WHEN NOT MATCHED THEN
  //insert into the table

This will return an error saying the following: 这将返回一条错误消息,内容如下:

Msg 10739, Level 15, State 1, Line 10 消息10739,第15级,州1,第10行
The insert column list used in the MERGE statement cannot contain multi-part identifiers. MERGE语句中使用的插入列列表不能包含多部分标识符。 Use single part identifiers instead. 请改用单个零件标识符。

I'm not sure how I would remove the multi-part identifiers and still have this work... since I need to define which database we are looking in. 我不确定如何删除多部分标识符,但仍然有这项工作...,因为我需要定义我们要查找的数据库。

Any ideas on how I would get around this? 关于如何解决这个问题有什么想法吗? Any help would be appreciated 任何帮助,将不胜感激

This works for me: 这对我有用:

MERGE INTO db1.dbo.TempCat B
USING (
  SELECT CategoryID
  FROM db2.dbo.TempCat) E
ON (B.CategoryID = E.CategoryID)
WHEN MATCHED THEN
  UPDATE SET CategoryID = E.CategoryID
WHEN NOT MATCHED THEN
  INSERT (CategoryID) VALUES (E.CategoryID);

I think the problem was the extra E. after SELECT -- you're defining E, so you can't use it there. 我认为问题是SELECT之后出现了多余的E.您正在定义E,因此无法在其中使用它。 No multi-part identifier needed. 无需多部分标识符。

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

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