Question

If I have the following SQL block (in SQL SERVER 2008 R2):

BEGIN
    BEGIN TRAN

    DELETE FROM dbo.fooData
    WHERE LastUpdate < DateAdd(hour, -1,GETUTCDATE())

    COMMIT

    BEGIN TRAN

    DELETE FROM dbo.barData
    WHERE SessionID NOT IN (SELECT sub.SessionId FROM dbo.fooData sub)

    COMMIT
    RETURN 0
END

I am assuming that I have to do an explicit COMMIT between the statements in order for the deleted data from fooData to show up in the second delete. Is this correct? Ideally, I'd want all of this to be in one transaction. Example:

BEGIN
    BEGIN TRAN

    DELETE FROM dbo.fooData
    WHERE LastUpdate < DateAdd(hour, -1,GETUTCDATE())

    DELETE FROM dbo.barData
    WHERE SessionID NOT IN (SELECT sub.SessionId FROM dbo.fooData sub)

    COMMIT
    RETURN 0
END

My fear is that the second statement will not pick up the first's deleted data. Note, the return is there because this is part of a stored procedure. I am not interested in cascading deletes or joining, I am somewhat constrained to this method.

Was it helpful?

Solution

The same transaction/session can see it's own changes. Other sessions won't see these uncommitted transactions from this session

So your 2nd form (one wider transaction) is safe to use.

OTHER TIPS

You can use the second example.

Because you're in the same transaction, you are accessing to the information of the previous operations.

Isolation says that other operations cannot access data that has been modified during a transaction that has not yet completed. The question of isolation occurs in case of concurrent transactions (multiple transactions occurring at the same time). but you are int the same transaction, so that transaction can and will access to the result of first operation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top