Tuesday, February 24, 2009

T-SQL How to drop connections and detach a database?

sp_detach_db system stored procedure do the detaching job on a database from server, also It will run UPDATE STATISTICS on all tables before detaching.

Note: To be able to execute sp_detach_db you need to have right permission and only members of the sysadmin role can execute it.

sp_detach_db
   [@dbname =] 'dbname'
   [, [@skipchecks =] 'skipchecks']

[@dbname =] 'dbname'
It's the name of the database which you want to detach it, it's default value is NULL.
[@skipchecks =] 'skipchecks'
Default value is NULL.
If true, UPDATE STATISTICS will be skipped.
If false, UPDATE STATISTICS will run.
skipchecks data type is nvarchar(10)

If you want to move your database to a read onlu media, this option is useful

0 returns If the procedure executes with success
1 returns If the procedure encounter with error (failure)

An important matter is that, if there is a connection to database, you can't detach it, the following code will drop connections and the detach your database from server:

USE master
GO
ALTER DATABASE myDbName
   SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
EXEC sp_detach_db @dbname = 'myDbName', @skipchecks = 'true'
GO

Share/Bookmark

No comments: