Skip to content

Instantly share code, notes, and snippets.

@danmalcolm
Last active December 10, 2015 21:48
Show Gist options
  • Save danmalcolm/4497458 to your computer and use it in GitHub Desktop.
Save danmalcolm/4497458 to your computer and use it in GitHub Desktop.
Example of some custom code to clear data from a table with a self-referencing FK constraint
DELETE FROM ...
IF EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_Customer_Customer_MergedToCustomerId]') AND parent_object_id = OBJECT_ID(N'[dbo].[Customer]'))
ALTER TABLE [dbo].[Customer] DROP CONSTRAINT [FK_Customer_Customer_MergedToCustomerId]
DELETE FROM [dbo].[Customer]
ALTER TABLE [dbo].[Customer] WITH CHECK ADD CONSTRAINT [FK_Customer_Customer_MergedToCustomerId] FOREIGN KEY([MergedToCustomerId])
REFERENCES [dbo].[Customer] ([CustomerId])
ALTER TABLE [dbo].[Customer] CHECK CONSTRAINT [FK_Customer_Customer_MergedToCustomerId]
DELETE FROM ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment