SQL Server 2005
In order to set your SQL Server 2005 database in a read only mode, first make sure there are no users connected to the database. Once you are sure of that, use the sp_dboption stored procedure to modify database settings
Use the following query. In the query, we make the database read only after first checking if there are no users connected to the db. The Variable @CntConn = 0 means there are no users connected.
DECLARE @CntConn smallint
SELECT @CntConn = count(spid) FROM sys.sysprocesses
WHERE db_name(dbid) = 'Northwind'
if @CntConn < 1
EXEC sp_dboption "Northwind", "read only", "TRUE";
PRINT @CntConn
If someone now attempts to change any data in the database, he is encountered with the following error message
To set the database back to write only mode, use this query:
EXEC sp_dboption "Northwind", "read only", "FALSE";
Note: Now if there are a few users connected and you want to disconnect them forcefully, then check this post of mine Obtain Exclusive Access to Database While Performing Maintenance Tasks in SQL Server
SQL Server 2008
sp_dboption does work in SQL Server 2008, however it should not be used. According to BOL,
This feature will be removed in the next version of Microsoft SQL Server. Do not use this feature in new development work, and modify applications that currently use this feature as soon as possible. Use ALTER DATABASE instead.
So to make a database read only in SQL Server 2008, use this query
USE master;
GO
ALTER DATABASE Northwind
SET READ_ONLY;
GO
1 comment:
Hi,
How could we put an SQL server 2008 in READ_WRITE mode?
Is it with this code :
USE master;
GO
ALTER DATABASE Northwind
SET READ_WRITE;
GO
Thanks for this post!
Post a Comment