我有表Listings
, Media
它是“源”数据库的子表Listings
并基于ListingId
“源”数据库进行链接,并且我在“目标”数据库中有相同的表。
将所有列表复制到目标表 将列表及其子项复制到目标Media
表,请记住,目标Media
表必须获取ListingId
插入到目标Listings
表的内容,这是一个identity column
INSERT INTO Listings ( Title, ...)
SELECT Title..
FROM [source].[dbo].Listings
WHERE ListingId IN (
SELECT s.ListingId
FROM [source].[dbo].Listings s
LEFT JOIN Listings d ON s.ImportedReferenceNumber = d.ImportedReferenceNumber
WHERE d.ListingId IS NULL
);
-- Insert corresponding media records into destination.Media table with new ListingIds.
INSERT INTO Media ( ListingId, Url, ThumbnailUrl, TypeId)
SELECT New.ListingID, Url, ThumbnailUrl, TypeId
FROM [source].[dbo].Media m
INNER JOIN (
SELECT s.ListingId, d.ListingId AS NEW_ListingId
FROM [source].[dbo].Listings s
LEFT JOIN Listings d ON s.ImportedReferenceNumber = d.ImportedReferenceNumber
WHERE d.ListingId IS NULL
) AS NEW ON m.ListingId = NEW.ListingId;
第一部分工作正常,但没有任何内容插入到目标中,因为执行查询时,源表和目标表Media
之间没有区别Listings