如果表中有一个外键,如何从表中删除?
我有这个存储过程但是当我执行它时它会给我这个错误:The DELETE statement conflicted with the REFERENCE constraint "FK__Pilot_Fli__pilot__4E88ABD4". The conflict occurred in database "Airline Reservation", table "dbo.Pilot_Flight", column
'pilot_id'。
create procedure DeletePilot
(@id INTEGER,@result varchar(70) output)
as
If NOT Exists ( Select * From Pilot
Where pilot_id=@id)
Begin
Set @result='There is no record with that ID'
RETURN
END
Delete from Pilot
where pilot_id=@id
set @result='Record was deleted'
RETURN
GO
select * from Pilot
Declare @res varchar(70)
EXEC DeletePilot 7,@res OUTPUT
print(@res)
任何人都可以帮助我!
答案 0 :(得分:2)
您必须运行这样的语句(如果它是nullable
):
UPDATE Pilot_Flight
SET pilot_id = NULL
WHERE pilot_id = @id
或者这样做:
DELETE Pilot_Flight WHERE pilot_id = @id
无论哪种方式,您都必须在<{1}} DELETE
之前之前执行之前的。
答案 1 :(得分:1)
dbo.Pilot_Flight中有记录在dbo.Pilot中引用记录。
您可以删除Pilot_Flight中的记录,然后删除Pilot中的记录,启用(cascade delete,当Pilot记录被删除(坏)时会删除Pilot_Flight中的记录,或者禁用外键引用...(更差) )。