我有一个脚本来通过检查外键的存在来更新数据库,如果它不存在,则创建它。它是由 SQL Management Studio 生成的。
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_tblChangeRequestForecast_tblCostingCenter]') AND parent_object_id = OBJECT_ID(N'[dbo].[tblChangeRequestForecast]'))
ALTER TABLE [dbo].[tblChangeRequestForecast] WITH CHECK ADD CONSTRAINT [FK_tblChangeRequestForecast_tblCostingCenter] FOREIGN KEY([CostingCenterID])
REFERENCES [dbo].[tblCostingCenter] ([CostingCenterID])
GO
IF EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_tblChangeRequestForecast_tblCostingCenter]') AND parent_object_id = OBJECT_ID(N'[dbo].[tblChangeRequestForecast]'))
ALTER TABLE [dbo].[tblChangeRequestForecast] CHECK CONSTRAINT [FK_tblChangeRequestForecast_tblCostingCenter]
GO
该脚本在运行时会引发错误:
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_tblChangeRequestForecast_tblCostingCenter". The conflict occurred in database "mydatabase", table "dbo.tblCostingCenter", column 'CostingCenterID'.
这是非常神秘的。就查询而言,没有外键的踪迹,但创建脚本失败并出现上述错误。服务器正在运行 SQL Server 2005 SP3 (9.00.4035.00)。
[更新]:我刚刚在 SQL Server 2012 实例上重现了该问题。所以版本似乎不太重要。
知道是什么原因造成的吗?