Reputation: 2522
I am attempting to migrate some data from one database to another using Microsoft SQL Server. Both databases have a "Properties/Locations" type of table that is referenced by a foreign key.
Unfortunately, even though the entities referenced in the two tables are the same, the primary keys are not. As such, in order to migrate the data, I am trying to temporarily disable the foreign key constraint, insert and update the data appropriately, and then re-enable the constraint.
However, I am receiving the following message:
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK__TwelveCri__Store__114A936A". The conflict occurred in database "API", table "dbo.Properties", column 'ID'.
While, I understand the general reason why the error is being thrown (it is not finding a match between the column StoreID
in the Reports
table and the ID
columns in Properties
), I do not understand why it is doing so in this specific case.
BEGIN TRAN
USE API;
EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT ALL";
SET IDENTITY_INSERT Midamcorp.TwelveCriticalsReports ON;
INSERT INTO Midamcorp.TwelveCriticalsReports (ID, StoreID, InspectorName, ReportTime, ReportDate, PointsPoss, PointsReceived)
SELECT
id, storeID, inspectorName, reportTIme, reportDate, pointsPoss, pointsReceived
FROM
midAmCorp.dbo.criticalReports;
SET IDENTITY_INSERT Midamcorp.TwelveCriticalsReports OFF;
UPDATE API.Midamcorp.TwelveCriticalsReports
SET StoreID = 1
WHERE StoreID = 4;
!--- MORE UPDATE STATEMENTS HERE ---!
USE API
SET IDENTITY_INSERT Midamcorp.SecretShopperReportSummary ON;
INSERT INTO Midamcorp.SecretShopperReportSummary(ID, StoreID, PointsPoss, PointsReceived, DriveTime, CompletedBy, DateOfVisit)
SELECT
id, storeID, pointsPoss, pointsReceived, driveTime, completedBy, dateOfVisit
FROM
midamCorp.dbo.secretShopperReportSummary;
SET IDENTITY_INSERT Midamcorp.SecretShopperReportSummary OFF;
!--- MORE UPDATE STATEMENTS HERE ---!
USE API
SET IDENTITY_INSERT Midamcorp.SecretShopperReportDetails ON;
INSERT INTO Midamcorp.SecretShopperReportDetails(ID, ReportID, QuestionID)
SELECT
id, reportID, questionID
FROM
midAmCorp.dbo.secretShopperReportDetails;
SET IDENTITY_INSERT Midamcorp.SecretShopperReportDetails OFF;
SELECT *
FROM Midamcorp.TwelveCriticalsReports
WHERE StoreID NOT IN (SELECT StoreID FROM dbo.Properties);
EXEC sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT ALL";
COMMIT TRAN;
The SELECT
statement at near the end returns no results, which is what I would expect if the relationships were properly updated. However, I am still receiving the error message noted above, presumably from the EXEC sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT ALL";
statement.
Any advice would be appreciated.
Upvotes: 0
Views: 355