2

Would like to do multiple updates via my API using mssql transactions.

Example:

  1. Shipping Table
  2. Listing Table
  3. User_Notes Table
  4. Customer_Login Table
  5. Push_Notification Table

Which is the right way of doing it?

I was thinking at first of doing it with raw queries.

BEGIN TRANSACTION

CREATE IN SHIPPING

UPDATE IN LISTING

CREATE IN USER_NOTES

UPDATE IN CUSTOMER_LOGIN

CREATE IN PUSH_NOTIFICATION

COMMIT

But want to avoid writing a big raw query like this.

Also can I use mssql Transactions and Queries with (request.query).

const transaction = new sql.Transaction(/* [pool] */)
transaction.begin(err => {
    // ... error checks

    const request = new sql.Request(transaction)
    request.query('create in shipping table', (err, result) => {
        // ... error checks

        transaction.commit(err => {
            // ... error checks

            console.log("Transaction committed.")
        })
    })

    request.query('Update in Listing Table', (err, result) => {
        // ... error checks

        transaction.commit(err => {
            // ... error checks

            console.log("Transaction committed.")
        })
    })

    and so on...
    .
    .
    .
})
Dhaval Jardosh
  • 7,151
  • 5
  • 27
  • 69
  • A big batch is actually more efficient as there is less round trips. I would use `SET XACT_ABORT ON` at the top of the batch, to ensure the transaction is not left hanging in case of an exception – Charlieface Sep 22 '21 at 20:44
  • The code isn't structured properly because it calls `transaction.commit` inside each request. That should only be called when all requests have completed successfully, so you either nest requests inside one another and only call `transaction.commit` on the innermost one, or you fire off all requests asynchronously and call `transaction.commit` when `Promise.all` completes or `transaction.rollback` if it rejects. – AlwaysLearning Sep 22 '21 at 21:49

0 Answers0