Hello, this article is going to be part2 of How To Fix: XTP Configuration Is Invalid where we have learnt about the SCOM alert, what is XTP in SQL Server and how to fix the same in stand alone SQL Instance.
Here we’ll learn about the steps to fix XTP Configuration is invalid error in Always On SQL Instance. Hence I would like you to first go through the first article.
Steps to Fix Configuration Is Invalid Error In Always On
Calculate Resource Pool Memory
Create a resource pool
Bind the database to the pool
Bring the database offline and then online
Confirm the Binding
Now you may be thinking, well these are exactly the same steps for stand alone SQL Instance. Yes, you’re right, however in case of Always On you need to perform few extra steps for the point no. 4.
I have already explained how to calculate resource pool memory in the first article Link. Here I’ll start from point no.2
2. Create a resource pool
In case of Always On you have to create the resource pool in all the replicas.
Execute the below query on each replica.
CREATE RESOURCE POOL PoolName --Provide the pool name maintaining Organization's naming convention WITH
(
MIN_MEMORY_PERCENT = 63, --Adjust as needed/calculated
MAX_MEMORY_PERCENT = 63 --Often set to the same value as MIN_MEMORY_PERCENT for Predictability
)
GO ALTER RESOURCE GOVERNOR RECONFIGURE;
Hi There! Whether you are a student, aspiring data professional, or thinking to transform to a DBA role and wondering “What Does SQL DBA Actually Do”, you are not alone. The title Database Administrator (DBA) might sound mysterious, but it’s one of the most critical roles in IT .
This guide breaks down what a SQL Server DBA really does, the tools they use and additional responsibilities as they grow in their carrier.
There are basically two type of DBA jobs in the IT industry.
Application DBA/Logical DBA — Works closely with Application Developers. Designs schema, tables, indexes, and relationships according to application needs. Require Strong SQL coding skills.
Production/Infrastructure DBA — Focuses on database operations, uptime, performance, and recovery in the production environment. Demands Strong system administration and database configuration skills.
To give you one real time scenario to understand a basic difference between the two:
When a Query is running slow, Production DBA will identify the exact slow running query and provide the query(execution) plan to App DBA. App DBA will analyze the plan and fix the query.
In some organizations the responsibilities may overlap depending upon the job requirement.
Key Responsibilities of a SQL Server DBA:
Area
Application DBA
Production DBA
Database Backup & Recovery
Is not Responsible
Ensure all database servers are backed up in alignment with Recovery Point Objective (RPO) and regularly
tests restores of the backup files to make sure Recovery Time Objective (RTO) can be met.
Database Design
Designs schema, tables, indexes, and relationships according to application needs.
Ensures design aligns with operational standards and performance requirements.
SQL & Performance
Tunes SQL queries, stored procedures, and application-side performance.
Tunes system-level performance—memory, I/O, CPU, and indexing strategies.
Development Support
Works with developers during development and testing phases.
Supports deployments, migrations, and production rollouts.
Maintenance
Less involved in backups and system maintenance.
Handles patching, upgrades, Index maintenance and monitoring.
Security & Access
Defines roles and privileges for applications.
Manages overall database security, auditing, and compliance.
Troubleshooting
Fixes app-specific data or query issues.
Diagnoses system-level issues, server crashes, corruption, and performance bottlenecks.
Essential Tools/Functionalities Every SQL Server DBA Should Know:
Tool
Description
SQL Server Management Studio (SSMS)
Core interface for managing SQL databases.
Azure Data Studio
Modern, cross-platform alternative with notebooks.
SQL Server Extended Events
For tracing and debugging query performance.
Dynamic Management Views (DMVs)
Provides insight into SQL Server to assist with troubleshooting and monitoring.
SQL Agent Service
Automates scheduled jobs and maintenance tasks.
PowerShell / dbatools
For automating DBA workflows.
Query Store
Simplifies the process of identifying and resolving Query performance issues by providing insights into query plan.
Monitoring Tool like Redgate SQL Toolbelt
Professional suite for monitoring, comparison, and deployments.
Now as you grow in your DBA carrier, your role will not be limited to only technical work. I have tried to put few more critical responsibilities based on my experience.
Automation: Analyze repetitive tasks and check what and how far a task can be automated. Work with automation team, provide suggestions etc.
Incident reduction: Senior DBA/leads will work on analyzing ticket dumps and work on reducing repetitive incidents on same SQL Instance.
RCA (Root Cause Analysis) : On P1/P2 incidents, Leads/SME (Subject Matter Specialist) will work with Problem Management Team to document the RCA.
SOP (Standard Operating Procedure): You’ll be responsible for preparing SOPs for junior resources or on particular process to be followed for repetitive activities. e.g. Steps to Follow from database end during OS patching, Database Decommission, SQL Instance Provision/Decommission etc.
Customer Escalations: Handling customer escalations will be one of your prime responsibilities.
Mentoring Junior DBAs: Guiding Junior DBAs and providing necessary technical/process related trainings. Making proper plan for newly onboarded team member to bring him/her up to the speed etc.
Planning Major Activities: You will need to prepare Runbooks for major activities like DR (Disaster Recovery Drill), SQL Server upgrades etc.
Hope now you have got an overall idea about what Does a SQL DBA Actually Do. Please feel free to comment in case you want me to add any further responsivities.
Hi There! In this article we are going to discuss about the SCOM Alert “MSSQL On Windows: XTP Configuration Is Invalid”. At first let’s see the alert description:
“XTP configuration for database “DatabaseName” on SQL Server instance “SQLInstance Name”, computer “ServerName” is not set according to the best practices. Database with memory-optimized tables should be bound to a dedicated resource pool.”
This alert points to issues with the configuration of In-Memory OLTP (XTP) features in SQL Server, which can impact database performance and reliability. As per the alert description, the database has memory-optimized tables and there is no dedicated resource pool. That is why you are not going to find out any error in SQL Error log related to this.
What is XTP in SQL Server?
XTP stands for Extreme Transaction Processing, an informal name to describe the In-Memory OLTP feature that powers memory-optimized tables. It is to boost transaction throughput by minimizing disk I/O and maximizing data access speed.
When you enable and create memory-optimized tables, SQL Server requires specific settings and prerequisites to ensure the XTP engine runs smoothly.
What is the Impact on SQL Server?
SQL Engine will allocate memory to memory-optimized tables from the default pool. This leads to uncontrolled memory consumption, which can cause overall memory pressure.
Without proper resource pools, SQL Server cannot isolate memory for In-Memory OLTP.
Result: potential server performance degradation, query slowdowns, or even crashes causing downtime.
How to Fix the XTP Configuration is Invalid Error?
Calculate Resource Pool Memory
Create a resource pool
Bind the database to the pool
Bring the database offline and then online
Well it is not that simple as it sounds. You need to calculate the memory percentage to allocate to the resource pool.
First of all you need to know the amount of memory needed for the memory optimized tables in the database. You can go through the Microsoft documentation Estimate Memory Requirements for Memory-Optimized Tables for the same.
Ideally this number should be provided by the app team to production DBA to do the rest of the configuration in SQL Server. However in some cases your app team may not be able to help with the information. Then you need to proceed as per the size in pre prod environment by monitoring the growth for couple of weeks.
memoryNeeded: Amount of memory needed for memory optimized tables
memoryCommitted: SQL Server Max Memory
availablePercent: Refer the below table:
Target Committed Memory
Percent available for in-memory tables
<= 8 GB
70%
<= 16 GB
75%
<= 32 GB
80%
<= 96 GB
85%
>96 GB
90%
For example, If
memoryNeeded = 16 GB
memoryCommitted = 32 GB
then availablePercent (considering the table) = 80%
Hence by plugging real numbers
percentNeeded = 16 / (32 * .8) = 16/25.6 =.625
Converting the result to percentage .625 * 100 = 62.5
percentNeeded = 62.5% rounding of to 63%
Create a resource pool:
Execute the following script to create a resource pool:
CREATE RESOURCE POOL PoolName --Provide the pool name maintaining Organization's naming convention WITH
(
MIN_MEMORY_PERCENT = 63, --Adjust as needed/calculated
MAX_MEMORY_PERCENT = 63 --Often set to the same value as MIN_MEMORY_PERCENT for Predictability
)
GO ALTER RESOURCE GOVERNOR RECONFIGURE;
e.g.
Just to clarify, resource pool is created at SQL Instance level and not on database.
Next and last step is to take the database offline and than bring it online as can be seen in the messages once you bind the database to the resource pool.
Hello, Today we I am going to provide you with a query to List SQL Database Role Owner Across All Databases. In the article Query To List SQL Database Role Owner we have seen how to List The Database Role Owner for a single Database.
This query will be nice to have in the repository in case you want a audit report for all databases on a SQL Instance.
DECLARE @dbname VARCHAR(50)
DECLARE @statement NVARCHAR(MAX)
CREATE TABLE #databaseRoleOwner
(
[DatabaseName] sysname,
[RoleName] varchar(100),
[RoleOwner] varchar(100)
);
DECLARE db_cursor CURSORLOCAL FAST_FORWARD
FOR
SELECT name
FROM master.sys.databasesWHERE state_desc='online'OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @dbname
WHILE @@FETCH_STATUS = 0
BEGINSELECT @statement = 'use ['+@dbname +'];'+ 'SELECT dbname=db_name(db_id()),
name AS RoleName,
USER_NAME(owning_principal_id) AS RoleOwner
FROM
sys.database_principals
WHERE
type = ''R'' and name NOT IN (''public'', ''db_owner'', ''db_accessadmin'',''db_securityadmin'', ''db_ddladmin'',''db_backupoperator'',''db_datareader'',
''db_datawriter'',''db_denydatareader'',''db_denydatawriter'')'INSERT INTO #databaseRoleOwner ([DatabaseName],[RoleName],[RoleOwner])
EXEC sp_executesql @statement
FETCH NEXT FROM db_cursor INTO @dbname
ENDCLOSE db_cursor
DEALLOCATE db_cursor
SELECT * FROM #databaseRoleOwner
GO -- DROP TABLE #databaseRoleOwner
Example Result set:
Let me know your thoughts by leaving comments below. The following scripts are also useful for day to day DBA life.
Hi There! Today I am going to provide you with a simple Query To List SQL Database Role Owner. Understanding who owns a role helps database administrators (DBAs) track permissions and audit role management effectively.
Where Do you See the Database Role Owner?
In SSMS (SQL Server Management Studio), Expand the Database > Security > Roles > Database Roles > Right Click on the Role > Properties
Possible Scenarios:
These are few possible cases when you may need to to list out the Database Role Owners.
Review current role ownership across multiple databases.
Ensure roles are owned by intended users or service accounts.
Document security settings for compliance.
Query To List SQL Database Roles and the Owner:
USE SQLGeeksPro
GOSELECT Dbname=DB_NAME(DB_ID()),
name AS RoleName,
USER_NAME(owning_principal_id) AS RoleOwner
FROM
sys.database_principals
WHWRE
Type='R'
Hi There! This is going to be a quick guide for SQL Server FORMAT Function. Formatting data in SQL Server often plays a crucial role in reporting, data presentation, and user interfaces.
Here we’ll walk you through few examples of the FORMAT() function in SQL Server.
Introduced in SQL Server 2012, the FORMAT() function is used to return a value formatted with the specified format and culture (locale).
It is particularly useful when you need to:
Display results in a user-friendly format
Output locale-specific formats
Customize currency or date formats
2. Syntax of FORMAT()
It has a very simple Syntax
FORMAT( value , format [ , culture ] )
Now let’s understand the parameters:
Value: It is the value on which you want to apply the formatting. Not to mention, it should be one of the valid data types.
Format: Specify the format in which you require the output. (for example, "MM/DD/YYYY"). It does not support Composite formatting. This parameter should contain a valid .NET format string in the NVARCHAR data type
Culture: It is an optional parameter. By default, SQL Server uses the current session language. This language is set either implicitly, or explicitly by using the SET LANGUAGE statement.
Culture accepts any .NET Framework supported culture as an argument or else it raises an error.
3. Formatting Dates and Times
You can use FORMAT() to format date and time values using .NET date and time format strings.
Example 1: Formatting current Date in ‘yyyy-mm-dd’ or ‘dd-mm-yyyy’ format
SELECT GETDATE() AS DefaultDateFormat
GOSELECT FORMAT(GETDATE(),'yyyy-MM-dd') AS FormattedDate
GOSELECT FORMAT(GETDATE(),'dd-MM-yyyy') AS FormattedDate
GO
The result set is as follows:
In this case you can observe that the default date format of GETDATE() function is “yyyy-mm-dd hh:mm:ss.mmm” and we used the FORMAT() function to display it in “yyyy-mm-dd” and “dd-mm-yyyy” format.
Example 2: Display/Extract desired format from GETDATE()
SELECT FORMAT(GETDATE(),'d') AS ShortDateGOSELECT FORMAT(GETDATE(),'D') AS LongDateGOSELECT FORMAT(GETDATE(),'m') AS MonthDateGOSELECT FORMAT(GETDATE(),'g') AS [MM/DD/YYYY hh:mm AM/PM]GOSELECT FORMAT(GETDATE(),'G') AS [MM/DD/YYYY hh:mm:ss AM/PM]GO
You can observe the differences in result set for each parameter:
4. Formatting Numbers:
You can apply numeric format strings for currency, percentages, and custom number formats
Example1: Formatting Numbers
SELECT FORMAT(1234.56, '#,##0.00') AS [Comma Separated Formatted Number];
GOSELECT FORMAT(1234.56, '#,##0.000') AS [Comma Separated Formatted Number With Additional Decimal Place];
GOSELECT FORMAT(123456789, '#,#') AS [Thousand Separator];
GOSELECT FORMAT(123456789.566, '#,#.##') AS [Thousand Separator with rounded to a specified number of decimal places]
GOSELECT FORMAT(123456789, '##-##-#####') AS [Dash Separator];
GO
Notice the differences in output. Column names are self explanatory.
Example 2: Formatting Currency
SELECT FORMAT(1.5, 'c', 'hi-in') AS [Indian Currency / Rupee] GO SELECT FORMAT(1.5, 'c', 'en-US') AS [US Currency / Dollar] GO SELECT FORMAT(1.5, 'c', 'en-gb') AS [Great Britain Currency / Pound] GO SELECT FORMAT(1.5, 'c', 'de-de') AS [German Currency / Euro] GO SELECT FORMAT(1.5, 'c', 'ru-ru') AS [Russian Currency / Ruble] GO SELECT FORMAT(1.5, 'c', 'gl-es') AS [Spain Currency / Euro] GO
The result set with self explanatory column names:
Example 3: Percentage Formatting
SELECT FORMAT(0.756, 'P') AS [Percentage] GO SELECT FORMAT(0.756, 'P0') AS [WholeNumberPercentage] GO SELECT FORMAT(0.756, 'P3') AS [ThreeDecimalsPercentage] GO SELECT FORMAT(0.756, 'P4') AS [FourDecimalsPercentage] GO SELECT FORMAT((47.0/48.0), '#,##.0%') AS [Percentage Rounded to One Decimal Place] GO SELECT FORMAT((47.0/48.0), '#,##.##%') AS [Percentage Rounded to Two Decimal Places] GO
Result set with self explanatory column names:
5. Specifying Culture (Locale)
Now let’s see formatting dates into different languages with the culture parameter.
SELECT FORMAT(GETDATE(), 'd','hi-in') AS [Indian (hi-in) (DD-MM-YYYY)] GO SELECT FORMAT(GETDATE(), 'd','en-US') AS [US English (en-US) (MM/DD/YYYY)] GO SELECT FORMAT(GETDATE(), 'd','en-gb') AS [Great Britain English (en-gb) (DD/MM/YYYY)] GO SELECT FORMAT(GETDATE(), 'd','de-de') AS [German (de-de) (DD.MM.YYYY)] GO SELECT FORMAT(GETDATE(), 'd','zh-cn') AS [Chinese (zh-cn) (YYYY/MM/DD)] GO SELECT FORMAT(GETDATE(), 'd','ru-ru') AS [Russian (ru-ru) (DD.MM.YYYY)] GO SELECT FORMAT(GETDATE(), 'd','gl-es') AS [Spain (gl-es) (DD/MM/YYYY)] GO
Please note the self explanatory column names for each:
Conclusion
The FORMAT() function is an incredibly flexible tool in SQL Server, ideal for making your output more user-friendly and internationalized. While it should be used with care in terms of performance, it greatly simplifies the formatting of numbers and dates compared to older methods.
Start using FORMAT() in your reporting queries to make your data presentation cleaner and more consistent.
Hello! If you’re working with SQL Server and need to filter records based on a date range, you’re in the right place. In this article, we’ll discuss how to select data between two dates in SQL Server using best practices to ensure accuracy and performance. Date filtering is a common task when analyzing time-bound records irrespective you being SQL developer or production DBA.
Reasons to Select Data Between Two Dates:
You want to check the successful backups happened between two dates
What the are indexes which were part of Index maintenance in last couple of weekends
What is the data/log file growth in a month etc.
When working with large datasets, retrieving only the relevant time-based records helps.
Microsoft SQL Server provides different methods to select data between two dates. The most common ones are as follows:
BETWEEN Operator
Arithmetic Operators Greater Than (>) and Less Than (<)
SELECT Data Between Two Dates in SQL Server Using BETWEEN Operator:
The BETWEEN keyword is inclusive, that means it includes both the start and end dates.
Syntax:
SELECT * FROM [TableName] WHERE [DateColumn]
BETWEEN 'StartDate' AND 'EndDate'--Ensure the date format matches the column data type (YYYY-MM-DD is recommended).
Now let’s take an example. Assume you have the following data in a SalesInfo table:
You want to extract the sales data between 2021-01-10 and 2025-02-28 (yyyy-mm-dd), the query would be as follows:
SELECT * FROM [SalesInfo] WHERE [DateOfPurchase]
BETWEEN '2021-01-10' AND '2025-02-28'--Ensure the date format matches the column data type (YYYY-MM-DD is recommended).
Pay attention to the Result set, you can see that both the dates are included.
It was pretty simple isn’t it. Now let’s see how stuff works if the date column is of type Datetime/Datetime2.
Make a note of the underlined datetime in red:
Execute the same query for ‘SalesData’ table and let’s compare the result sets:
Important to realize here is the underlined datetime value has not appeared in the result set though we said that BETWEEN operator is inclusive. Well, the catch here is when you specify the only date for a column of having data type Datetime/Datetime2 it simply considers midnight (12 am).
In other words SQL Engine interprets ‘2021-01-10‘ as ‘2021-01-10 00:00:00.000’ and ‘2025-02-28’ as ‘2025-02-28 00:00:00.000′. Because ‘2025-02-28 21:26:54.000’ is greater than ‘2025-02-28 00:00:00.000’, it is not included.Now you know why SQL omitted the underlined date in the above example.
SELECT Data Between Two Dates using Arithmetic Operators Greater Than (>) and Less Than (<)
These operators allows the flexibility to include or exclude the start and end dates by specifying equal operator along with them. That means if you use >= and <= it will work just like BETWEEN operator. Again if you are dealing with Datetime/Datetime2 data type, the same concept of midnight applies as described above.
Let’s consider the SalesInfo table where the data type for the date column is Date.
SELECT * FROM [SalesInfo]
WHERE [DateOfPurchase] >= '2021-01-10'AND [DateOfPurchase] <='2025-02-28'
The result set shows that both the dates are included:
As mentioned earlier it has the flexibility to exclude any of the dates. In the below example the end date is excluded by mentioning (<) operator.
SELECT * FROM [SalesInfo]
WHERE [DateOfPurchase] >= '2021-01-10'AND [DateOfPurchase] <'2025-02-28'
Conclusion:
Selecting SQL Server data between two dates is a fundamental but powerful task. Whether you’re using BETWEEN, >= AND <, the key is understanding how SQL Server handles date and time. With these techniques, you can write efficient and accurate queries to get the data you need.
Hi there! In this article we are going to discuss how to resolve the error “The database could not be exclusively locked to perform the operation. (Microsoft SQL Server, Error: 5030)”
You need to have exclusive lock on the database to rename the db. Exclusive lock means there are no other database connections open/using the database. SQL Engine is smart enough not to allow database name change while other users are accessing the database.
Query to Resolve Database could not be exclusively locked:
Following query will switch the database from Multi User mode to Single User mode, then rename the database and then set it back to Multi User mode.
USE master
GOALTER DATABASE [DatabaseName] --Change The Database NameSET SINGLE_USER WITH ROLLBACK IMMEDIATEGOALTER DATABASE [DatabaseName] MODIFY NAME = [NewDatabaseName]
GOALTER DATABASE [NewDatabaseName] --Put the new database nameSET MULTI_USER WITH ROLLBACK IMMEDIATE
Point often overlooked in the above query is the final statement, where you need to put the new database name.
To demonstrate please find the following Example for database named “SQLGeeksPro” renaming to “SQLGeeksPro_NewName”
This article is in continuation of How To Rename SQL Server Database and here we are going show how to Rename SQL Database Logical and Physical File Names.
I am sure you have already got the idea from the previous article on what is logical and physical file name. The query we used to check the database file details is as follows: We are going to use this multiple times to verify the file details.
USE SQLGeeksPro_NewName -- Change the db NameGOSELECT DB_NAME() AS DatabaseName, file_id, name AS logical_name, physical_name
FROM sys.database_files
GO
Now we are going to rename SQL Database logical and physical file name.
Now let’s check the database file details again by executing the first query.
Example result set:
As can be seen till now we are able to rename the database name and logical file name. Next and final step is to rename the physical file name.
Things become a bit tricky here as you can’t rename physical files while the database is online. Therefore I had mentioned in the first article that you need downtime.
Steps To Rename SQL Database Physical File Name:
To rename physical file name we have to take the database offline and for that we need exclusive access to the database and hence we’ll first put the database in Single User mode. If there are any transactions running from application, it’s recommended to let them complete first.
In the below query, first statement will rollback any open transactions and set the database in single user mode. The second statement will put the database into offline state.
Step1: Put the database in Offline State
USE master
GOALTER DATABASE [SQLGeeksPro_NewName] SET SINGLE_USER WITH ROLLBACK IMMEDIATEGOALTER DATABASE [SQLGeeksPro_NewName] SET OFFLINE
In SSMS the database status will look like below:
Step2: Rename the Physical Files
Go to the physical locations of data and log file and rename them. Below screen shot shows example for primary data file. You have to rename all the data and log files in respective physical locations.
Step3:Update System Catalog
You have to inform SQL Server Engine that physical file name have been changed for the data and log files so that when you bring up the database it can refer the metadata and identify the new names. Otherwise it will try to look for the the old physical file names and will fail to bring the database online.
The message shows that the system catalogs have been updated and new path will be used after the database is started.
Step4: Bring up the database using the below query
USE master
GOALTER DATABASE [SQLGeeksPro_NewName] SET ONLINEGOALTER DATABASE [SQLGeeksPro_NewName] SET MULTI_USER
Final step is to verify if all files have been renamed successfully as desired/as per organization standards.
You can execute the very first query provided in this article again:
Conclusion:
As can be seen above, renaming a SQL Server database can be done easily with a few steps. Rename not only SQL Server database alone but also logical and physical file names.
Feel free to leave your thoughts below in comment sections.
Hi There! Today we are going to discuss How To Rename SQL Server Database the best way. Renaming a SQL Server database can be a straightforward process, but it is essential to follow the right steps to ensure data integrity and avoid disruptions. Trust me most of the DBAs think it is too easy to perform and end up missing an essential step which is discussed here.
Why Rename SQL Server Database?
Before jumping into the steps, it’s important to understand why you might need to rename a database. Common reasons are as follows:
Rebranding: Aligning the database name with a new organizational structure or branding.
Clarity: Improving the descriptiveness of the database name for better understanding among team members.
Organization: Consolidating database names for better management in multi-database environments.
Version Control: Adding version numbers or dates for better tracking.
Regardless of the reason, there may come a time when you want to or need to rename a database. In this tip we’ll look at the best option.
Prerequisites to Rename SQL Server Database:
First ensure the following:
Backups: Always have a recent backup of your database. This provides a safety net in case something goes wrong during the renaming process.
Permissions: Verify that you have the necessary permissions to rename the database. Typically, you need to be a member of the db_owner role or have ALTER permission
Downtime: The process needs downtime and hence always secure downtime approval/inform stake holders as per your organization process.
Two Different Methods can be used to Rename SQL Server Database:
Using SSMS (SQL Server Management Studio)
Using T-SQL
First of all let’s check and note the database details by running the following query:
USE SQLGeeksPro -- Change the db NameGOSELECT DB_NAME() AS DatabaseName, file_id, name AS logical_name, physical_name
FROM sys.database_files
GO
The Results will be as shown below:
Make a note of the highlighted details in the above example.
Rename SQL Database using SSMS:
Step 1: Connect to SQL Server
Open SQL Server Management Studio (SSMS) and connect to the SQL Server instance that contains the database you want to rename.
Step 2: Right click on the database and select the Rename option
Step 3: Type in the new name you want for the database
Now if you are not able to rename it because of the error message “The database could not be exclusively locked to perform the operation. (Microsoft SQL Server, Error: 5030)” then refer Database could not be exclusively locked
Rename SQL Database using T-SQL:
Step1: In SSMS open a new Query Window
Step2: Execute the below Query:
USE master
GOALTER DATABASE [CurrentDatabaseName] MODIFY NAME = [NewDatabaseName] -- Change the CurrentDatabaseName and NewDatabaseName as required
For Example:
This command works for SQL Server 2005, 2008, 2008R2, 2012, 2014, 2016, 2017, 2019 and 2022. Alternatively you can use sp_renamedb as well.
USE master
GOEXEC sp_renamedb 'CurrentDatabaseName','NewDatabaseName'
Most of us think that in this way we have completed the database renaming. In other words you’ll be able to see the new name in SSMS. Important to realize and point often overlooked is we have not changed the logical and physical file name. To be sure execute the very first query provided above to check the file names:
Result will be as shown below:
As can be seen in the highlighted portion in green, only the database name got changed and there is no change for logical and physical file names. This may cause confusion in future even if we keep the technical issues aside. We can discuss it in another blog post.
Therefore you need to change the logical and physical file names as well. >>Continue Reading