Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 SQL Server Development (2000)
 Delete Record and all assoctiated?

Author  Topic 

MikeB
Constraint Violating Yak Guru

387 Posts

Posted - 2004-03-03 : 11:10:37
How do I delete one record from one table and cascade down all related tables?

Mike B

X002548
Not Just a Number

15586 Posts

Posted - 2004-03-03 : 11:44:24
I've never put this in a production system...so I haven't tested performance...I guess that's the real issue...


USE Northwind
GO

CREATE TABLE myTable99(Col1 char(1) PRIMARY KEY,Col2 varchar(25))
GO

CREATE TABLE myTable00(Col1 char(1), Col1a char(1), Col2 varchar(25)
, PRIMARY KEY (Col1, Col1a)
, FOREIGN KEY (Col1) REFERENCES myTable99(Col1)
ON DELETE CASCADE
ON UPDATE CASCADE
)
GO

INSERT INTO myTable99(Col1,Col2)
SELECT 'A','The Letter A' UNION ALL
SELECT 'B','The Letter B' UNION ALL
SELECT 'C','The Letter C'
GO

INSERT INTO myTable00(Col1,Col1a,Col2)
SELECT 'A','1','The Letter A' UNION ALL
SELECT 'B','2','The Letter B' UNION ALL
SELECT 'C','3','The Letter C' UNION ALL
SELECT 'A','4','The Letter A' UNION ALL
SELECT 'B','5','The Letter B' UNION ALL
SELECT 'C','6','The Letter C'
GO

SELECT * FROM myTable99
SELECT * FROM myTable00
GO

UPDATE myTable99 SET Col1 = 'D' WHERE Col1 = 'A'
GO

SELECT * FROM myTable99
SELECT * FROM myTable00
GO

DELETE FROM myTable99 WHERE Col1 = 'B'
GO

SELECT * FROM myTable99
SELECT * FROM myTable00
GO

DROP TABLE myTable00
DROP TABLE myTable99
GO




Brett

8-)
Go to Top of Page

JohnDeere
Posting Yak Master

191 Posts

Posted - 2004-03-05 : 00:48:33
SQL 2000 supports cascading deletes.
I have also used triggers to accomplish this.

Lance Harra
Go to Top of Page

JimL
SQL Slinging Yak Ranger

1537 Posts

Posted - 2004-03-05 : 08:59:53
Generally when I have direct relationship tables I create a trigger on the primary to delete the associated records in the sub tables. and place them in a deleted table for safekeeping for a period of time.

Example:

CREATE TRIGGER SOHead_DelRecTrigger
ON dbo.SOHead
FOR DELETE
AS
Set nocount On

DELETE FROM dbo.SOdet

FROM Deleted INNER JOIN
dbo.SODet ON Deleted.ORID = dbo.SODet.ORID

INSERT INTO dbo.SOHeaderDeleted
(ORID, CustID, ShiptoID)
SELECT Deleted.ORID, Deleted.CustID, Deleted.ShiptoID

From Deleted


Jim
Users <> Logic
Go to Top of Page

mohdowais
Sheikh of Yak Knowledge

1456 Posts

Posted - 2004-03-05 : 10:57:17
Cascade Delete is what you want, but be very careful...you could lose a lot of data in no time. You can do it yourself inside a single transaction in a stored proc, you will have more control over it this way. This way, you can also audit deletes, or copy the data to another table like Jim demonstrates.

OS
Go to Top of Page
   

- Advertisement -