我想实现删除3个相关表中的行的过程。
我有桌子,A,B和C.
Table A
ID
Table B
ID
tableAId
Table C
ID
tablceBId
关系表A - B是一对多,关系B - C是一对多。
现在我想实现一个删除与表A相关的所有行的过程。我不想在级联上删除这些行。我可以在一个查询中实现这一点吗?
我在表A中传递了行ID。
答案 0 :(得分:1)
CREATE PROCEDURE delTableA
@tableA_ID int
AS
BEGIN
DELETE C
FROM C
INNER JOIN B ON C.ID = B.tableCId
INNER JOIN A ON B.ID = A.tableBId
WHERE A.ID = @tableA_ID
DELETE B
FROM B
INNER JOIN A ON B.ID = A.tableBId
WHERE A.ID = @tableA_ID
DELETE FROM A
WHERE A.ID = @tableA_ID
END
GO
如同,
CREATE TABLE C (ID int)
CREATE TABLE B (ID int, tableCId int)
CREATE TABLE A (ID int, tableBId int)
GO
INSERT INTO c VALUES (1)
INSERT INTO b VALUES (1, 1)
INSERT INTO a VALUES (1, 1)
GO
CREATE PROCEDURE delTableA
@tableA_ID int
AS
BEGIN
DELETE C
FROM C
INNER JOIN B ON C.ID = B.tableCId
INNER JOIN A ON B.ID = A.tableBId
WHERE A.ID = @tableA_ID
DELETE B
FROM B
INNER JOIN A ON B.ID = A.tableBId
WHERE A.ID = @tableA_ID
DELETE FROM A
WHERE A.ID = @tableA_ID
END
GO
EXEC delTableA 1
GO
如果您运行此查询,则全部为空:
select * from A
select * from B
select * from C