Quantcast
Channel: SQL Backup Archives - SQL Authority with Pinal Dave
Viewing all articles
Browse latest Browse all 110

SQL SERVER – Attach a Database with T-SQL

$
0
0

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]
GO
CREATE DATABASE [AdventureWorks] ON 
( FILENAME = N'D:\Data\AdventureWorks.mdf' ),
( FILENAME = N'E:\Log\AdventureWorks_log.ldf' )
 FOR ATTACH
GO

Method 2: sp_attach_db

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

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

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)

First appeared on SQL SERVER – Attach a Database with T-SQL


Viewing all articles
Browse latest Browse all 110

Trending Articles