SQL Server - 使用EXEC时更改表FOREIGN KEY冲突sp_msforeachtable

时间:2017-11-02 14:43:49

标签: sql-server sp-msforeachtable

我正在尝试使用Microsoft SQL Server将一些数据从一个数据库迁移到另一个数据库。两个数据库都有一个"属性/位置"外键引用的表的类型。

不幸的是,即使两个表中引用的实体相同,主键也不是。因此,为了迁移数据,我试图暂时禁用外键约束,适当地插入和更新数据,然后重新启用约束。

但是,我收到以下消息:

  

ALTER TABLE语句与FOREIGN KEY约束冲突" FK__TwelveCri__Store__114A936A"。冲突发生在数据库" API",table" dbo.Properties",column' ID'。

虽然,我理解错误被抛出的一般原因(但StoreID表中的Reports列与{ID列之间找不到匹配1}}),我不明白为什么在这个具体案例中这样做。

Properties

接近结尾的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; 语句不会返回任何结果,如果关系得到适当更新,这就是我所期望的。但是,我仍然收到上面提到的错误消息,可能来自SELECT声明。

任何建议都将受到赞赏。

0 个答案:

没有答案