Question : Update records in SQL table via Excel VBA and ADO

I have Excel worksheets updating tables in SQL Server, via ADO and VBA. This I do by
DELETE existing records
INSERT new records on the worksheet
This works fine.

The problem is, in the rare instances when the INSERT process crashes (!) the DELETE has already happened and the INSERT is only part, up to where it crashed. (fortunately the data is still sitting on the worksheet, so not the end of the world)

Have tried and UPDATE-OR-INSERT alternative, but this can give rise to duplicates.

Can someone suggest a better, fool-proof way?

ROLLBACK TRANSACTION was mentioned. Does anyone have an example? How capture SQL's messages back to VBA to alert the user?

Or a really clever solution to this?
Thanks!

Answer : Update records in SQL table via Excel VBA and ADO

This is an example of transaction that could do the job for you.
It was partly taken from:
http://bytes.com/topic/access/insights/677490-ado-transaction-processing
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
        On Error GoTo Err_Handler
        Dim cnn As ADODB.Connection
        Dim blnInTrans As Boolean

        blnInTrans = False        'not in a Transaction as of yet
        cnn = CurrentProject.Connection
        '...

        cnn.BeginTrans()
        blnInTrans = True       'now in the beginning of a Transaction

        'Do your delete here

        'Do your insert here

        cnn.CommitTrans()
        blnInTrans = False      'Transactions completed without Error

        '...

Exit_Handler:
        Exit Sub

Err_Handler:
        If blnInTrans Then      'in the midst of a Transaction
            cnn.RollbackTrans()     'Restore data to pre-Transaction state
            ' This will restore the data deleted by your DELETE query
        End If
        'further Error processing here
        Resume Exit_Handler
Random Solutions  
 
programming4us programming4us