• junk.mail291276 - Thursday, March 22, 2018 4:31 PM

    Hello,

    We have a database transaction. During this transaction, the database is locked so that other process can't access the
    database. 90% of the time, the process which is blocked simply waits for the transaction to end. When it ends, they can
    access the database again. However, the other 10% of the time, we get a deadlock error:

    "Transaction was deadlocked on lock resources with another process and has been chosen as the deadlock victim."

    Under what conditions does a database transaction block another transaction, and under what conditions does it become
    deadlocked with another transaction (resulting in one of the transactions being killed)?

    First, transactions and blocking are not scoped at the entire database level. Read up more about how [transaction scope], [lock granularity], and [isolation level] works.

    To avoid deadlocks, keep the transactions as short as possible. In other words, don't BEGIN TRAN, update data, select a bunch of data that takes a long time, and then COMMIT TRAN several minutes or hours later. With long running transactions, the window of opportunity for multiple transactions to overlap and become entangled, thus resulting in a deadlock, is much more likely. Instead, first select what you need, perhaps into a temp table, and then only perform the update operations within the transaction block.

    Also, when bulk updating millions of rows, do so in batches of 100,000 rows at a time, with a commit in between, so each transaction is shorter and hold it's locks on a smaller subset of the table. If you're updating more than a few hundred thousand rows at a time, SQL Server may even escalate the lock from page level to table level.

    As for keeping users out of the database during off hour maintenance or deployments, you can alter the database to restricted user mode (recommended over single user mode), meaning that only members of sysadmin role can connect, and then set status back to muli-user mode when done.

    "Do not seek to follow in the footsteps of the wise. Instead, seek what they sought." - Matsuo Basho