SQL SERVER – Attach a Database with T-SQL

To attach a Database with T-SQL, I use CREATE DATABASE … FOR ATTACH. A customer asked about attaching existing data and log files.

Matched drawer components await fitting beside preserved original materials.

-- Reviewed attach template. Paths are on the SQL Server host.
-- USE master;
-- CREATE DATABASE [AdventureWorks] ON
-- (FILENAME = N'D:\Data\AdventureWorks.mdf'),
-- (FILENAME = N'E:\Log\AdventureWorks_log.ldf') FOR ATTACH;
-- Historical deprecated alternative, not recommended for new work:
-- EXEC sys.sp_attach_db @dbname=N'AdventureWorks',
-- @filename1=N'D:\Data\AdventureWorks.mdf',
-- @filename2=N'E:\Log\AdventureWorks_log.ldf';

My original example showed two methods. sp_attach_db is deprecated and appears only as historical syntax. Include every required file. Verify they belong to a consistent detached or offline database.

Paths refer to the SQL Server host, whose service identity needs access. Check supported database version and features. A newer engine can upgrade files so an older engine can’t reopen them. Recreate and validate server-level dependencies separately.

Preserve original files and a restore-tested backup. Incomplete, untrusted or ransomware-damaged files need an appropriate recovery investigation. Don’t delete a log file merely to force a rebuild. The linked attach and failure cases offer context.

Reference: Database attachment requirements.

Related reading

An attach command is not a recovery guarantee, it is a file-based operation with consistency and compatibility requirements.

Published by Pinal Dave on SQLAuthority. More of my work at pinaldave.com.


Discover more from SQL Authority with Pinal Dave

Subscribe to get the latest posts sent to your email.

In-Memory OLTP, SQL Backup and Restore, SQL Scripts, SQL Server
Previous Post
Capture sp_who2 Output Into a Table With INSERT EXEC
Next Post
Attach an In-Memory Database With T-SQL: Include the Container

Related Posts

Leave a Reply

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

Fill out this field
Fill out this field
Please enter a valid email address.