Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to attach a SQL Server database from the command line

Is it possible to enter a command line command (like in a batch file) to attach a detached database to SQL Server, in stead of opening the management studio and doing it in there?

like image 455
Michel Avatar asked May 06 '10 19:05

Michel


2 Answers

you need to use: sqlcmd Utility

The sqlcmd utility lets you enter Transact-SQL statements, system procedures, and script files at the command prompt, in Query Editor in SQLCMD mode, in a Windows script file or in an operating system (Cmd.exe) job step of a SQL Server Agent job. This utility uses OLE DB to execute Transact-SQL batches.

Then use CREATE DATABASE (Transact-SQL) to do the attach and sp_detach_db (Transact-SQL) to do the detach. The sp_attach_db (Transact-SQL) is going to be removed in a future version of Microsoft SQL Server.

like image 141
KM. Avatar answered Sep 19 '22 05:09

KM.


If you need to specify the log file name: USE master; GO; CREATE DATABASE DBNAME ON ( FILENAME = 'C:\DBFILE.mdf') LOG ON ( FILENAME = 'C:\DBLOGFILE_log.ldf') FOR ATTACH; GO; And to detach: USE master; GO; EXEC sp_detach_db 'DBNAME', 'true'; GO;

like image 28
paul-2011 Avatar answered Sep 21 '22 05:09

paul-2011