I want to empty a temporary table, load it via bcp, and then modify its rows before moving to a production table. The commands would look something like this:
- truncate table temp1
- bcp db.schema1.temp1 in import1.txt -h “TABLOCK”
- exec sp_modify_temp1_rows_move_to_production_table
My question is how can I execute all this as one transaction, not necessarily in the interest of rolling it back, but in order to provide isolation.
Here is the imagined scenario. User1 goes to load import1.txt (the implementation details of how this done, steps 1-3, are hidden to the user). Before step 2 finishes for User1, User2 initiates their own import. Locking mechanisms prevent their import from starting right away. The primary concern is that User2 step 1 will begin as soon as User2’s step 2 is done thus clearing the table before User1’s step 3 and the process can be completed.
Three additional notes:
- Client side execution here via ADO (not to be mistaken with ADO.NET)
- BULK INSERT is NOT an option
- Prefer doing this via extending some lock mechanism via ADO that can include step 2 in with steps 1 and 2 of the process – if possible – knowing that it is impossible helps here also.
The typical solution is to use applocks acquired via
This way you locks a logical resource (an arbitrary string/name) and, by convention, other users attempting to do the same must attempt to obtain the same applock. While the applock is held, the
bcpcommand can run w/o interference. Note that this does not prevent another user/application that does not respect the protocol (because of ignorance, malevolence or stupidity).