Can't Set SINGLE_USER Mode in Availability Group or Database Mirroring
I recently learnt that when a database is part of Availability Group or in Database mirroring, it can’t be set in SINGLE_USER mode.
Context
I was working on modifying isolation level of database from Read Committed to Read Committed Snapshot(RCSI) and had to get exclusive access to the database. After letting the application team know about it and having stopped their processes, I tried to set the database to SINGLE_USER but it errored out.
Query:
ALTER DATABASE DBATest
SET SINGLE_USER WITH ROLLBACK IMMEDIATE
Error:
The operation cannot be performed on database "DBATest" because it is involved in a database mirroring session or an availability group. Some operations are not allowed on a database that is participating in a database mirroring session or in an availability group. ALTER DATABASE statement failed.
Workaround
After confirming all app services related to that database are not connected anymore, checked the connections and killed stale ones if any and made sure there were no connections to the database. Then, executed READ_COMMITTED_SNAPSHOT WITH ROLLBACK IMMEDIATE. This finished in less than a minute. Even WITH ROLLBACK IMMEDIATE, if there are new connections constantly coming in or there are long running transactions, it does get hard to get exclusive access on the database.
Database is still in MULTI_USER mode, but since there were no long running transactions, the command was easily able to get exclusive (X) lock on the database.
Conclusion:
If you’re trying to set SINGLE_USER mode on a database involved in an Availability Group setup or Database Mirroring, keep in mind that it isn’t possible unless you remove the database from these configurations or you may have to find a workaround. Also, I couldn't find any online documentation that talks about this, which I think is odd.
Hope this helps anyone running into similar issues!
If you’re interested to learn how to set Read Committed Snapshot Isolation (RCSI) in your database, here is the link.
Thanks for reading,
Haripriya.