patternsqlMinor
Can db_datareader user block ALTER TABLE statement?
Viewed 0 times
canstatementuserblockdb_datareaderaltertable
Problem
db_datareader user tries to update and gets an error:
User doesn’t close session.
User with enough rights tries to alter the table afterwards and gets blocked:
Executing query ..
Is this normal behavior?
BEGIN TRAN
UPDATE [TestDB].[dbo].[Table_1]
SET Col1 = 'Test';
Msg 229, Level 14, State 5, Line 3
The UPDATE permission was denied on the object 'Table_1', database 'TestDB', schema 'dbo'.User doesn’t close session.
User with enough rights tries to alter the table afterwards and gets blocked:
BEGIN TRAN
ALTER TABLE [TestDB].[dbo].[Table_1]
ADD Col2 INT;Executing query ..
Is this normal behavior?
Solution
Yes. The first query has left an open transaction. SQL Server doesn't check if the current user has permissions at compile time. It will find out at run time. If you were writing a stored procedure you wouldn't want to check permissions at compile time as a different user may execute the procedure.
Wrapping the UPDATEs, in both queries, in a TRY CATCH would avoid leaving an open transaction.
Wrapping the UPDATEs, in both queries, in a TRY CATCH would avoid leaving an open transaction.
BEGIN TRY
BEGIN TRAN
UPDATE [TestDB].[dbo].[Table_1]
SET Col1 = 'Test';
COMMIT TRAN
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK;
;THROW;
END CATCHCode Snippets
BEGIN TRY
BEGIN TRAN
UPDATE [TestDB].[dbo].[Table_1]
SET Col1 = 'Test';
COMMIT TRAN
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK;
;THROW;
END CATCHContext
StackExchange Database Administrators Q#164649, answer score: 4
Revisions (0)
No revisions yet.