Attach File mdf to SQL Server using Command Prompt Sqlcmd

Attach Database File *.mdf to SQL Server using Command Prompt SqlcmdAttach File mdf to SQL Server using Command Prompt Sqlcmd | Sometimes we need to attach a database file * .mdf and * .ldf into the database sqlserver especially sqlserver express edition. Usually we use sqlserver management studio, but if there is some condition that does not possible to us to use SQL Server Management Studio, then we must use sqlcmd, SQL Server Command Prompt.

First, click Windows Start Button, at Run input type “cmd”, when “Command Prompt” menu show up, right click menu select Run as administrator.

Use Command Prompt SqlCmd

After the DOS command prompt show up, type the following command:

sqlcmd -S <server>\<instance name>

If you are using SQL Server Express Edition use this command:

sqlcmd -S .\SQLEXPRESS

Then type this following command according to the location database file * .mdf and * .ldf, and the name of the desired database.

USE [master]
GO
CREATE DATABASE [database_name] ON
( FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\.mdf' ),
( FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\.ldf' )
FOR ATTACH ;
GO

Attach Database File *.mdf to SQL Server using Command Prompt Sqlcmd

Done, we should now have entered the database file attached to SQL Server database as a new database.

Verify If Database Succesfully Attached

To make sure database has been attached, type the following commands:

select name from sys.databases
go

Attach Database File *.mdf to SQL Server using Command Prompt Sqlcmd Verify

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>