2014-01-15 139 views
0

如何從表中刪除行,如果它有外鍵? 我有這個存儲過程,但是當我執行它時,它給了我這個錯誤: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'。從Sql Server中的表中刪除行

create procedure DeletePilot 
    (@id INTEGER,@result varchar(70) output) 
as 
    If NOT Exists (Select * From Pilot 
      Where [email protected]) 
    Begin 
     Set @result='There is no record with that ID' 
     RETURN 
    END 

    Delete from Pilot 
    where [email protected] 
    set @result='Record was deleted' 
    RETURN 
GO 
select * from Pilot 
Declare @res varchar(70) 
EXEC DeletePilot 7,@res OUTPUT 
print(@res) 

任何人都可以幫助我!

回答

2

你必須要麼運行這樣的語句(如果是nullable):

UPDATE Pilot_Flight 
SET pilot_id = NULL 
WHERE pilot_id = @id 

或做到這一點:

DELETE Pilot_Flight WHERE pilot_id = @id 

你必須做一個無論哪種方式或其他之前DELETEPilot

+1

第二個工作。謝謝 – user3043278

+0

@ user3043278,我很高興我可以幫助! –

1

在dbo.Pilot_Flight中有記錄在dbo.Pilot中的記錄。

你可以在試點刪除記錄之前刪除Pilot_Flight的記錄,使能(cascade delete這將刪除Pilot_Flight記錄時,飛行員記錄被刪除(壞),或禁用外鍵參考...(差)。