插入语句与外键冲突

时间:2014-11-18 14:18:40

标签: sql-server database tsql stored-procedures

这里我尝试从其他源数据库表中插入事实表中的数据这里是我尝试的查询

alter procedure spfactinsert
as
insert into [pp dw].dbo.Dimfact(costprice,Prod_ID,Production_ID,MaterialQuantity,Quantity)

select [cost price],Products.[Product ID],Production_Detail.[ProdDetail ID],
[Material Quantity],Production_Detail.Quantity
 from
[PRODUCTION PLANNING 2].dbo.Production_Detail,
[PRODUCTION PLANNING 2].dbo.[Materials],
[PRODUCTION PLANNING 2].dbo.[Recipies],
[PRODUCTION PLANNING 2].dbo.Products

where 
Production_Detail.[ProdDetail ID]='1' and
[Materials].[Material ID]='1' and
[Recipies].[Recipy ID]='1'
and
Products.[Product ID]='13'

但它显示错误

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Dimfact_DimProduction". The conflict occurred in database "pp dw", table "dbo.DimProduction", column 'Production_ID'.

ERD是 IMAGE ERD

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

插入列表中的第一列是Quantity,但您选择cost price这是插入列表中的第二列。您正在Quantity插入导致FK违规的Production_ID

更改为:

insert into [pp dw].dbo.Dimfact(Quantity,costprice,Prod_ID,MaterialQuantity,Production_ID)
SELECT 
    Production_Detail.Quantity,
    [cost price],
    Production_Detail.[ProdDetail ID],
    [Material Quantity],
    Products.[Product ID]