我有2个表tlbinvoice
和tblRel_Inv_Course
,其中InvoiceID
是外键。当我尝试从Invoice
表中删除一行时,出现错误
无法删除外键约束
下面是两个查询和数据:
select * from invoice where InvoiceID=19
InvoiceID invimagetype location
-----------------------------------
19 image/jpeg network
select * from Rel_Inv_Course where CourseID=4262
Rel_I_C_ID CourseID InvoiceID
----------------------------------
2255 4262 19
我尝试过的:
delete from [TAP].[dbo].Invoice
where InvoiceID = (select InvoiceID
from Rel_Inv_Course
where CourseID = 4262)
delete from Rel_Inv_Course
where CourseID = 4262
但是我不能这样做。我需要从发票编号为19的表的两行中删除。请帮助。
答案 0 :(得分:4)
正如评论所说,您所需要做的就是翻转delete语句,您应该会很好:
您可以考虑将它们包装在begin tran中,以便您检查删除是否也删除了您想要的数据:
Begin Tran
DECLARE @INVOICEID INT
SET @INVOICE = (select InvoiceID from Rel_Inv_Course where CourseID=4262)
delete from Rel_Inv_Course where CourseID=4262
delete from [TAP].[dbo].Invoice where InvoiceID =(@INVOICEID)
--Select * from Rel_Inv_Course
--Select * from [dbo].Invoice
--If satisfied with deletes finally commit tran
--If not satisfied --> Rollback Tran
Commit Tran
答案 1 :(得分:0)
使用一些示例数据和DDL可能更易于解释:
(?<=_)\d\.\d
您会注意到USE Sandbox;
GO
CREATE TABLE dbo.Parent (ID int NOT NULL,
SomeString varchar(100) NOT NULL);
GO
CREATE TABLE dbo.Child (ID int NOT NULL,
ParentID int NOT NULL,
AnotherString varchar(100) NOT NULL);
GO
ALTER TABLE dbo.Parent ADD CONSTRAINT PK_PID PRIMARY KEY CLUSTERED (ID);
ALTER TABLE dbo.Child ADD CONSTRAINT PK_CID PRIMARY KEY CLUSTERED (ID);
ALTER TABLE dbo.Child
ADD CONSTRAINT FK_PID
FOREIGN KEY (ParentID)
REFERENCES dbo.Parent (ID);
GO
INSERT INTO dbo.Parent (ID,
SomeString)
VALUES (1, 'sdfkgjbhasdfg'),
(2, 'sdfkjsdbhkf');
GO
INSERT INTO dbo.Child (ID,
ParentID,
AnotherString)
VALUES (1, 1, 'asdfkiashjbd'),
(2, 1, '#asldjasbhdk,'),
(3, 2, 'asfjasdfj');
GO
--Try to delete a row in Parent:
DELETE FROM dbo.Parent
WHERE ID = 2;
--No surprise it failed
GO
--Try to delete a row in child
DELETE FROM dbo.Child
WHERE ID = 2;
--This worked fine.
GO
--
--If we check, however, ParentID 1 and 2 are still in the table:
SELECT *
FROM dbo.Child;
--We want to delete ID 1 in parent, so we need to delete the other row
DELETE FROM dbo.Child
WHERE ParentID = 1;
--Now delete in Parent
DELETE FROM dbo.Parent
WHERE ID = 1;
GO
DROP TABLE dbo.Child;
DROP TABLE dbo.Parent;
上的第一次删除失败,因为它与外键约束冲突。但是,删除该ID中子级中的所有行之后,您可以删除父级行。
相同的逻辑适用于您的数据。首先删除子表中的相关行,然后删除父表中的数据。或者,实现级联,然后只需要删除父级中的行,删除操作就会向下层叠。