A walk through of moving database files in SQL Server Always On Availability Groups

A walk through of moving database files in SQL Server Always On Availability Groups

A walk-through of moving database files in SQL Server Always On Availability Groups

SQLShack

SQL Server training Español

A walk-through of moving database files in SQL Server Always On Availability Groups

July 8, 2019 by Rajendra Gupta SQL Server Always On Availability Groups feature provides high availability (HA) and disaster recovery solutions. We can add multiple databases in a single Always on Availability Group on SQL Server Enterprise edition. Before we add a database in the AG group, we need to use the following checklist.

Checklist to add a database in SQL Server Always On Availability Group

The following checklist is applicable to add a database on Always On Availability Groups. We can add only User databases in an AG group The User database should be in a read-write mode. You can verify the database status using the following query 1234567 Select Case is_read_only When 1 then 'DB is in Read-Only Mode' When 0 then 'DB is in Read-Write Mode' End as Database_Status From sys.databases Where name='AdventureWorks2014' The database recovery model should be FULL. We can check the recovery model using the following query 123 Select recovery_model_desc From sys.databasesWhere name='AdventureWorks2014' Initiate a full recovery log chain using the full database backup. If we do not have an existing database backup, take a manual full database backup before adding a database into the AG group We cannot add a database into multiple availability groups The database must not set to Auto Close. We can verify it using the following query 1234567 Select Case is_auto_close_on When 1 then 'DB is in Auto Close Mode' When 0 then 'DB is not in Auto Close Mode' End as Database_Status From sys.databases Where name='AdventureWorks2014' We should have a similar location for both the data and log files on the primary and all applicable secondary replicas. Recently I come across an issue of low disk space on disk holding data file for a database in Always On Availability Groups. We can use the following approach to resolve the incidents for low disk space. Expand the data file disk size. It is the simplest method to resolve this issue. You can simply ask the storage or VM administrator to expand the disk to have sufficient free space If you have multiple data files for SQL database in SQL Server Always On Availability Group, you can plan to move some of the data files into another drive having sufficient free disk space The method to move data files on a database in Always On Availability Groups is different from the standalone database. Let’s explore the methods to move the data files in an Always On Availability Group.

Environment Details for this article

TestDB database in Synchronous data commit mode with automatic failover and readable secondary replica Data and log file for TestDB are in D:\TestDB folder. You can verify the data files path using the sp_helpdb ‘testDb’ command on both primary and secondary replica
Primary Replica data file locations Secondary Replica data file locations The database should be healthy and synchronized in SQL Server Always On Availability Group Dashboard. You can use the following query as well to check the synchronization status 123456789101112 SELECT sadc.database_name, ag.name AS ag_name, dhrs.is_local, dhrs.is_primary_replica, dhrs.synchronization_state_desc, dhrs.is_commit_participant, dhrs.synchronization_health_descFROM sys.dm_hadr_database_replica_states AS dhrs INNER JOIN sys.availability_databases_cluster AS sadc ON dhrs.group_id = sadc.group_id AND dhrs.group_database_id = sadc.group_database_id INNER JOIN sys.availability_groups AS ag ON ag.group_id = dhrs.group_id INNER JOIN sys.availability_replicas AS sar ON dhrs.group_id = sar.group_id AND dhrs.replica_id = sar.replica_id; Suppose D drive is having space issues, and we want to move the existing data file to another drive (E:\TestDB) having sufficient free space. We can use the following approach to do it.

Move data file to another drive in SQL Server Always On availability group database

In this approach, we have a small downtime requirement (we will cover it later with the steps). We configure the full and log backup on the AG database to prepare the database in case of any disaster. Take a log backup before the activity and disable all backups during the activity time. We should not break the backup chain else the restoration will not be possible. It ensures that the backup LSN (log sequence number) chain is intact and we are competent to perform restoration in case of any issues. Let’s move the data file into another drive using this method.

Steps to perform on Secondary replica in SQL Server Always on Availability Group

Step 1: Connect to the secondary replica and go to Always On High Availability. Expand the High Availability. Right-click on the database and suspend the data movement. It opens the following Suspend data movement wizard. Click on Ok to suspend data movement. Once the data movement is suspended, the database status on Secondary Always on Availability Group to Not Synchronizing. You can also see the health status of Not Healthy. Step 2: In this step, remove the database out from the SQL Server Always On Availability Group from the secondary replica. Expand the High Availability. Right-click on the database and Remove Secondary Database. It opens another wizard to remove a database from the AG group. Click on OK. Once you remove the database from the secondary replica AG group, it shows a warning sign with the database name in the Availability databases list. The Secondary AG database state changes to Restoring state. We removed the availability group database from SQL Server Always On Availability Group. The database is still available on the primary replica and available for the users. Only data synchronization between primary and secondary replica is not available. Step 3: Use the Alter database command on the master database of the secondary replica to move the data file to another drive. You can refer the article How to move SQL database files (MDF and LDF) to another location for more details on alter database command. 1234 ALTER DATABASE TestDB MODIFY FILE (NAME = TestDB, FILENAME = 'E:\TestDB\TestDB.mdf'); GO Once you execute this command, you get the following message: The file “TestDB” has been modified in the system catalog. The new path will be used the next time the database is started. Step 4: Stop the SQL Service on the secondary replica using the SQL Server Configuration Manager. Step 5: Move the database file to the new location and start the SQL Service. Execute the Sp_helpDB command to verify the data file location It still shows the old data file location on the secondary replica If we check using the database view sys.database_files, it also returns the wrong data file location 1234 Use TestDBGoSELECT name,physical_name FROM sys.database_files Sp_helpDB executes a stored procedure sp_helpfile, and its scope is set a database level. The secondary database is a replica of the primary in SQL Server Always On. In this article, we changed the data file location for the secondary database AG replica, but the primary database is still pointing to the old location. Secondary replica still gets the old data file path the primary replica. Due to this, we get old or incorrect data file locations using both sp_helpdb and sys.master_files commands for SQL Server Always On Availability Group. Let’s check the data file location using the system view sys.master_files. 1234 SELECT name, physical_name AS NewLocation, state_desc AS OnlineStatusFROM sys.master_files WHERE database_id = DB_ID(N'TestDB') GO It shows the correct location for the data file in the E drive. We get the correct results using the sys.master_files because this system view is scoped at the master database level. We have changed the system catalog in the master database on the secondary replica. The system database Master cannot be a part of the availability group. It is maintained separately for each instance. Due to this reason, we get the correct location of the data and log file on the secondary replica as well despite the different location of the data file on the primary replica. Note: You should always rely on the output of sys.master_file command instead of sp_helpdb and sys,database_files in SQL Server Always On availability group. Step 6: On the secondary replica, right-click on the database and click on Join to Availability Group. Once the database joins to an availability group, verify the status is synchronized. It might take a little time to become synchronized depending upon the number of transactions on the primary replica during the activity time.

Failover and perform the steps on new Secondary Server in SQL Server Always on Availability Group

Step 7: Perform a manual failover from the primary replica to secondary replica. After the failover, the old secondary replica becomes the primary, and we can verify the data file locations now using the sp_helpdb command. Step 8: Now, we need to perform the same steps 1 to 7 on the new secondary AG database. After this step, both the primary and secondary replica database is moved to E drive. Monitor the AG dashboard. Step 9: Enable both the full and log database backups on the AG replica (depending upon the backup configuration and priority on AG replica instances).

Conclusion

In this article, we learned to move the data file for SQL Server Always On Availability Group database. Try exploring this on the test environment and become familiar with the steps. Author Recent Posts Rajendra GuptaHi! I am Rajendra Gupta, Database Specialist and Architect, helping organizations implement Microsoft SQL Server, Azure, Couchbase, AWS solutions fast and efficiently, fix related issues, and Performance Tuning with over 14 years of experience.

I am the author of the book "DP-300 Administering Relational Database on Microsoft Azure". I published more than 650 technical articles on MSSQLTips, SQLShack, Quest, CodingSight, and SeveralNines.

I am the creator of one of the biggest free online collections of articles on a single topic, with his 50-part series on SQL Server Always On Availability Groups.

Based on my contribution to the SQL Server community, I have been recognized as the prestigious Best Author of the Year continuously in 2019, 2020, and 2021 (2nd Rank) at SQLShack and the MSSQLTIPS champions award in 2020.

Personal Blog: https://www.dbblogger.com
I am always interested in new challenges so if you need consulting help, reach me at [email protected]

View all posts by Rajendra Gupta Latest posts by Rajendra Gupta (see all) Copy data from AWS RDS SQL Server to Azure SQL Database - October 21, 2022 Rename on-premises SQL Server database and Azure SQL database - October 18, 2022 SQL Commands to check current Date and Time (Timestamp) in SQL Server - October 7, 2022

Related posts

Applying Transaction Logs to the Secondary Replica in SQL Server Always On Availability Groups SQL replication with a Publisher Database in Always On Availability Groups SQL Server Statistics in Always On Availability Groups Data synchronization in SQL Server Always On Availability Groups Isolation levels behavior in SQL Server Always On Availability Groups 29,559 Views

Follow us

Popular

SQL Convert Date functions and formats SQL Variables: Basics and usage SQL PARTITION BY Clause overview Different ways to SQL delete duplicate rows from a SQL Table How to UPDATE from a SELECT statement in SQL Server SQL Server functions for converting a String to a Date SELECT INTO TEMP TABLE statement in SQL Server SQL WHILE loop with simple examples How to backup and restore MySQL databases using the mysqldump command CASE statement in SQL Overview of SQL RANK functions Understanding the SQL MERGE statement INSERT INTO SELECT statement overview and examples SQL multiple joins for beginners with examples Understanding the SQL Decimal data type DELETE CASCADE and UPDATE CASCADE in SQL Server foreign key SQL Not Equal Operator introduction and examples SQL CROSS JOIN with examples The Table Variable in SQL Server SQL Server table hints – WITH (NOLOCK) best practices

Trending

SQL Server Transaction Log Backup, Truncate and Shrink Operations Six different methods to copy tables between databases in SQL Server How to implement error handling in SQL Server Working with the SQL Server command line (sqlcmd) Methods to avoid the SQL divide by zero error Query optimization techniques in SQL Server: tips and tricks How to create and configure a linked server in SQL Server Management Studio SQL replace: How to replace ASCII special characters in SQL Server How to identify slow running queries in SQL Server SQL varchar data type deep dive How to implement array-like functionality in SQL Server All about locking in SQL Server SQL Server stored procedures for beginners Database table partitioning in SQL Server How to drop temp tables in SQL Server How to determine free space and file size for SQL Server databases Using PowerShell to split a string into an array KILL SPID command in SQL Server How to install SQL Server Express edition SQL Union overview, usage and examples

Solutions

Read a SQL Server transaction logSQL Server database auditing techniquesHow to recover SQL Server data from accidental UPDATE and DELETE operationsHow to quickly search for SQL database data and objectsSynchronize SQL Server databases in different remote sourcesRecover SQL data from a dropped table without backupsHow to restore specific table(s) from a SQL Server database backupRecover deleted SQL data from transaction logsHow to recover SQL Server data from accidental updates without backupsAutomatically compare and synchronize SQL Server dataOpen LDF file and view LDF file contentQuickly convert SQL code to language-specific client codeHow to recover a single table from a SQL Server database backupRecover data lost due to a TRUNCATE operation without backupsHow to recover SQL Server data from accidental DELETE, TRUNCATE and DROP operationsReverting your SQL Server database back to a specific point in timeHow to create SSIS package documentationMigrate a SQL Server database to a newer version of SQL ServerHow to restore a SQL Server database backup to an older version of SQL Server

Categories and tips

►Auditing and compliance (50) Auditing (40) Data classification (1) Data masking (9) Azure (295) Azure Data Studio (46) Backup and restore (108) ►Business Intelligence (482) Analysis Services (SSAS) (47) Biml (10) Data Mining (14) Data Quality Services (4) Data Tools (SSDT) (13) Data Warehouse (16) Excel (20) General (39) Integration Services (SSIS) (125) Master Data Services (6) OLAP cube (15) PowerBI (95) Reporting Services (SSRS) (67) Data science (21) ►Database design (233) Clustering (16) Common Table Expressions (CTE) (11) Concurrency (1) Constraints (8) Data types (11) FILESTREAM (22) General database design (104) Partitioning (13) Relationships and dependencies (12) Temporal tables (12) Views (16) ►Database development (418) Comparison (4) Continuous delivery (CD) (5) Continuous integration (CI) (11) Development (146) Functions (106) Hyper-V (1) Search (10) Source Control (15) SQL unit testing (23) Stored procedures (34) String Concatenation (2) Synonyms (1) Team Explorer (2) Testing (35) Visual Studio (14) DBAtools (35) DevOps (23) DevSecOps (2) Documentation (22) ETL (76) ▼Features (213) Adaptive query processing (11) Bulk insert (16) Database mail (10) DBCC (7) Experimentation Assistant (DEA) (3) High Availability (36) Query store (10) Replication (40) Transaction log (59) Transparent Data Encryption (TDE) (21) Importing, exporting (51) Installation, setup and configuration (121) Jobs (42) ►Languages and coding (686) Cursors (9) DDL (9) DML (6) JSON (17) PowerShell (77) Python (37) R (16) SQL commands (196) SQLCMD (7) String functions (21) T-SQL (275) XML (15) Lists (12) Machine learning (37) Maintenance (99) Migration (50) Miscellaneous (1) ▼Performance tuning (869) Alerting (8) Always On Availability Groups (82) Buffer Pool Extension (BPE) (9) Columnstore index (9) Deadlocks (16) Execution plans (125) In-Memory OLTP (22) Indexes (79) Latches (5) Locking (10) Monitoring (100) Performance (196) Performance counters (28) Performance Testing (9) Query analysis (121) Reports (20) SSAS monitoring (3) SSIS monitoring (10) SSRS monitoring (4) Wait types (11) ►Professional development (68) Professional development (27) Project management (9) SQL interview questions (32) Recovery (33) Security (84) Server management (24) SQL Azure (271) SQL Server Management Studio (SSMS) (90) SQL Server on Linux (21) ►SQL Server versions (177) SQL Server 2012 (6) SQL Server 2016 (63) SQL Server 2017 (49) SQL Server 2019 (57) SQL Server 2022 (2) ►Technologies (334) AWS (45) AWS RDS (56) Azure Cosmos DB (28) Containers (12) Docker (9) Graph database (13) Kerberos (2) Kubernetes (1) Linux (44) LocalDB (2) MySQL (49) Oracle (10) PolyBase (10) PostgreSQL (36) SharePoint (4) Ubuntu (13) Uncategorized (4) Utilities (21) Helpers and best practices BI performance counters SQL code smells rules SQL Server wait types © 2022 Quest Software Inc. ALL RIGHTS RESERVED. GDPR Terms of Use Privacy
Share:
0 comments

Comments (0)

Leave a Comment

Minimum 10 characters required

* All fields are required. Comments are moderated before appearing.

No comments yet. Be the first to comment!

A walk through of moving database files in SQL Server Always On Availability Groups | Trend Now