Blogger Jeff = new Blogger

Programming and stuff in Western PA

Cascading deletes in SQL Server

I get asked from time to time if SQL Server supports cascading deletes, and the answer is Yes. SQL Server does so via foreign key constraints with the DELETE CASCADE flag set. In the following example, after creating the objects and inserting some data, we delete a USR_ID from the parent data. After querying the child table (USER_PHONE) a second time, we can see that the cascading delete worked :

CREATE TABLE USERS
(
    USR_ID int
    ,CONSTRAINT [PK_Temp_Users1] PRIMARY KEY CLUSTERED ([USR_ID])
)

CREATE TABLE USER_PHONE
(
    USR_ID int
    ,CONSTRAINT [PK_Temp_Users2] PRIMARY KEY CLUSTERED ([USR_ID])
)
ALTER TABLE [dbo].USER_PHONE  WITH CHECK ADD  
CONSTRAINT [FK_Temp_UsersPhone_Users] FOREIGN KEY([USR_ID])
REFERENCES [dbo].[Users] ([USR_ID])
ON DELETE CASCADE
GO

INSERT INTO USERS
    SELECT 1 UNION SELECT 2 UNION SELECT 3

INSERT INTO USER_PHONE
    SELECT 1 UNION SELECT 2 UNION SELECT 3

SELECT * FROM USER_PHONE
DELETE USERS WHERE USR_ID=2
SELECT * FROM USER_PHONE

DROP TABLE USER_PHONE
DROP TABLE USERS

Tags:

January 28, 2008 - Posted by | SQL Server, Technology

1 Comment »

  1. What about when you have two referential columns in the same table (e.g. ‘icon’ and ‘background’ both refer to the ‘image’ table)?

    In this example, SQL Server doesn’t allow both columns to have on-delete actions and I have to go back to stored procedures.

    It’s a ridiculous mess, and a bit shameful since it is 2010 and other databases have provided this functionality for years.

    Comment by Mike | April 12, 2010 | Reply


Leave a comment