views:

37

answers:

2

This deletes the document from the Document table and outputs information about the deleted document into the FinishedDocument table.

DELETE
FROM Document
OUTPUT Deleted.DocumentId
    , Deleted.DocumentDescription
INTO FinishedDocument
WHERE DocumentId = @DocumentId

I need to delete the document not just from the Document table, but also from the DocumentBackup table. Meanwhile, I need to maintain insertion into FinishedDocument.

Is all of this possible with only one statement? If not, is a second DELETE (against DocumentBackup), with all of it wrapped in a transaction, the way to go?

A: 

You'll need two DELETEs, but you should use two OUTPUTS on the first DELETE to do both the insert into FinishedDocument and into a table variable to save all of the deleted documents.

try:

DECLARE @DeletedDocuments table (DocumentId int)

BEGIN TRANSACTION

DELETE
    FROM Document
    OUTPUT Deleted.DocumentId, Deleted.DocumentDescription
        INTO FinishedDocument
    OUTPUT Deleted.DocumentId
        INTO @DeletedDocuments
WHERE DocumentId = @DocumentId

DELETE
    FROM DocumentBackup
    WHERE EXISTS (SELECT 1 FROM @DeletedDocuments d WHERE DocumentBackup.DocumentId=d.DocumentId)


COMMIT
KM
How might someone see this as preferable to two deletes (first against `BackupDocument`, and then against `Document`, with the OUTPUT clause to `FinishedDocument`) in a transaction?
lance
@lance, I'm not sure what you are asking? In any event you will have to have 2 DELETEs, with the INSERT coming from an OUTPUT clause. If you delete one table before the other, that would be a preference based on the activity of your application. I'd delete the least active table first, so if there are any locks they have less impact.
KM
A: 

As KM mentioned, it's 2 deletes.

Or a cascaded foreign key assuming you have a FK. Or a trigger.

gbn