SQL SERVER – Attach a Database with T-SQL

Yesterday one of my clients of Comprehensive Database Performance Health Check reached out to me asking for help in attaching the database files to the server. Let us see today we can attach a database with T-SQL.

SQL SERVER - Attach a Database with T-SQL withtsql-800x168

There are two different methods to attach the database. Let us see both of them.

Method 1: Create a Database with T-SQL

This is my preferred method and I use it all the time.

USE [master]
CREATE DATABASE [AdventureWorks] ON 
( FILENAME = N'D:\Data\AdventureWorks.mdf' ),
( FILENAME = N'E:\Log\AdventureWorks_log.ldf' )

Method 2: sp_attach_db

This is used to be my preferred method before I started to use Method 1.

USE [master]
EXEC sp_attach_db @dbname = N'AdventureWorks',   
    @filename1 =   'D:\Data\AdventureWorks.mdf',   
    @filename2 =   'E:\Log\AdventureWorks_log.ldf'

Well, that’s it. It is pretty simple to attach databases with the T-SQL script. Here is a few associated blog post on the same topic, which you may find useful.

If you have any such questions, you can reach me via Twitter.

Reference: Pinal Dave (https://blog.sqlauthority.com)

In-Memory OLTP, SQL Backup, SQL Restore, SQL Scripts, SQL Server
Previous Post
SQL SERVER – Inserting sp_who2 Into a Table
Next Post
SQL SERVER – Attach an In-Memory Database with T-SQL

Related Posts

Leave a Reply