I have tables Listings
and Media
which is a child table of Listings
and linked based on ListingId
in "source" database, and I have the same tables in "destination" dabase.
copy all listings to destination table Listings and its children to destination Media
table
keeping in mind that the destination Media
table has to get the ListingId
of what was inserted to the destination Listings
table and that is a 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;
The first part works fine, but nothing gets inserted into destination Media
because the query I have when executed, there is no difference between source and destination Listings
table