Thursday, April 02, 2009

Attach database

In MsSQL, a database can attach with system stored procedure sp_attach_db. The simplest way to execute this stored procedure is with this syntax

EXEC sp_attach_db ‘databaseName’, ‘path/to/database/file’

Or if you want to attach more than 1 file use this syntax

EXEC sp_attach_db ‘databaseName’, ‘path/to/database/file/1’ [,‘path/to/database/file/2’] [,‘path/to/database/file/3’]


You can attach database file up to 16 files. The ‘path/to/database/file’ should no more than 260 characters long.

This stored procedure is a shortcut for creating a database with syntax

CREATE DATABASE databaseName ON (FILENAME = ‘/path/to/database/file/1’ [,FILENAME = ‘/path/to/database/file/2’] [FILENAME = ‘/path/to/database/file/3’] […FILENAME = ‘/path/to/database/file/16’]) FOR ATTACH

FOR ATTACH required all data files, and if multiple log files exists, they must be attach to