CREATE Table A
(
AId int ,
AName varchar(100)
)
CREATE Table B
(
BId int,
AId int,
CId int,
BName varchar(100)
)
CREATE Table C
(
CId int,
CName varchar (100)
)
"A" has foreign key in "B" and "C" also has foreign key in B. Both foreign keys have Cascade delete enabled.
Foreign key :-
/****** Object: ForeignKey [FK_B_A] Script Date: 10/28/2010 17:20:16 ******/
ALTER TABLE [dbo].[B] WITH CHECK ADD CONSTRAINT [FK_B_A] FOREIGN KEY([AId])
REFERENCES [dbo].[A] ([AId])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[B] CHECK CONSTRAINT [FK_B_A]
GO
/****** Object: ForeignKey [FK_B_C] Script Date: 10/28/2010 17:20:16 ******/
ALTER TABLE [dbo].[B] WITH CHECK ADD CONSTRAINT [FK_B_C] FOREIGN KEY([CId])
REFERENCES [dbo].[C] ([CId])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[B] CHECK CONSTRAINT [FK_B_C]
GO
-- Sample data
INSERT INTO A
VALUES (1, 'Ashish')
INSERT INTO A
VALUES (2, 'Sanjay')
INSERT INTO A
VALUES (3, 'Vivek')
INSERT INTO B
VALUES
(1,1,10,'Ashish1')
INSERT INTO B
VALUES
(2,1,11,'Ashish2')
INSERT INTO B
VALUES
(3,1,12,'Ashish3')
INSERT INTO B
VALUES
(4,2,13,'Ashish1')
INSERT INTO B
VALUES
(5,2,14,'Sanjay')
INSERT INTO B
VALUES
(6,3,15,'Vivek')
INSERT INTO C
VALUES
(10, 'Ashish Data1')
INSERT INTO C
VALUES
(11, 'Ashish Data2')
INSERT INTO C
VALUES
(12, 'Ashish Data3')
INSERT INTO C
VALUES
(13, 'Ashish Data4')
INSERT INTO C
VALUES
(14, 'sanjay Data1')
INSERT INTO C
VALUES
(15, 'Vivek Data1')
I thought following would delete all data from all the tables:-
DELETE a FROM A a
INNER JOIN B ON A.AId = B.AId
INNER JOIN C ON B.CId = C.CID
instead I had to write this:-
DELETE a FROM A a
INNER JOIN B ON A.AId = B.AId
DELETE b FROM B b
INNER JOIN C ON B.CId = C.CID
Is there any way to delete all data in s single delete statement?