Thanks @mike01 I want to avoid Delete Cascade as I don't fully understand it.
These are all the FKs for the 3 related tables:
ALTER TABLE [dbo].[tblReturnDocumentSelections] WITH CHECK ADD CONSTRAINT [FK_tblReturnDocumentSelections_tblReturnDocument] FOREIGN KEY([ReturnDocumentID])
REFERENCES [dbo].[tblReturnDocument] ([ReturnDocumentID])
ALTER TABLE [dbo].[tblReturnDocumentSelections] WITH CHECK ADD CONSTRAINT [FK_tblReturnDocumentSelections_tblEstimate] FOREIGN KEY([EstimateID])
REFERENCES [dbo].[tblEstimate] ([EstimateID])
…..
ALTER TABLE [dbo].[tblReturnDocument] WITH CHECK ADD CONSTRAINT [FK_tblReturnDocument_tblReturnDocumentBatches] FOREIGN KEY([ReturnDocumentBatchID])
REFERENCES [dbo].[tblReturnDocumentBatches] ([ReturnDocumentBatchID])
GO
ALTER TABLE [dbo].[tblReturnDocument] WITH CHECK ADD CONSTRAINT [FK_tblReturnDocument_tblQuote] FOREIGN KEY([QuoteID])
REFERENCES [dbo].[tblQuote] ([QuoteID])
ALTER TABLE [dbo].[tblReturnDocument] WITH CHECK ADD CONSTRAINT [FK_tblReturnDocument_tblDODSubmittalStatus] FOREIGN KEY([DODSubmittalStatusID])
REFERENCES [dbo].[tblDODSubmittalStatus] ([DODSubmittalStatusID])
………
This is the table the Delete fails on:
ALTER TABLE [dbo].[tblReturnDocumentBatches] WITH CHECK ADD CONSTRAINT [FK_tblReturnDocumentBatches_tblQuote] FOREIGN KEY([QuoteID])
REFERENCES [dbo].[tblQuote] ([QuoteID])
The TSQL:
Declare @CompareDate char(10)
Set @CompareDate = (Select CompareDate from OzTest.dbo.OzTestCompareDate);
DELETE FROM Batches
FROM dbo.tblReturnDocumentBatches Batches
INNER JOIN dbo.tblQuote Q
ON Q.QuoteID = Batches.QuoteID
WHERE (Q.quostatus NOT IN ('Active', 'HOLD') AND Q.DownloadDate < @CompareDate);
The DELETE statement conflicted with the REFERENCE constraint "FK_tblReturnDocument_tblReturnDocumentBatches". The conflict occurred in database "OzTest", table "dbo.tblReturnDocument", column 'ReturnDocumentBatchID'.
I have tried running the deletes in various orders, - but this table always fails with the same FK error.
I'm not sure what my next steps are. Thanks