Database could not be exclusively locked Error 5030

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)”

The Complete error message while rename fails for exclusive lock looks like below: Refer How To Rename SQL Server Database

Database could not be exclusively locked

Why the Error Message:

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
GO
ALTER DATABASE [DatabaseName]  --Change The Database Name
SET SINGLE_USER  WITH  ROLLBACK  IMMEDIATE
GO
ALTER DATABASE [DatabaseName] MODIFY NAME = [NewDatabaseName]
GO
ALTER DATABASE [NewDatabaseName]  --Put the new database name
SET 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”

Database Could not be exclusively locked

Please spread the word:
RSS
Follow by Email
Facebook
Google+
https://sqlgeekspro.com/database-could-not-be-exclusively-locked/
Twitter
PINTEREST
LinkedIn

{ Add a Comment }

Rename SQL Database Logical and Physical File Names

<<Previous

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 Name
GO
SELECT 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.

Query to Rename SQL Database Logical File Name:
USE master
GO
ALTER DATABASE [SQLGeeksPro_NewName] MODIFY FILE (NAME = SQLGeeksPro, NEWNAME = SQLGeeksPro_NewName_Data);
GO
ALTER DATABASE [SQLGeeksPro_NewName] MODIFY FILE (NAME = SQLGeeksPro_log, NEWNAME = SQLGeeksPro_NewName_log);
GO

Rename SQL Database Logical and Physical File NameNow let’s check the database file details again by executing the first query.

Example result set:

Rename SQL Database Logical and Physical File Name

 

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
GO
ALTER DATABASE [SQLGeeksPro_NewName] SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
ALTER DATABASE [SQLGeeksPro_NewName] SET OFFLINE

Rename Logical and Physical File Name

In SSMS the database status will look like below:

Rename Logical and Physical File Name

 

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.

 

Rename Logical and Physical File Name

Rename Logical And Physical File Name

 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.

USE master
GO
ALTER DATABASE [SQLGeeksPro_NewName] MODIFY FILE (NAME ='SQLGeeksPro_NewName_Data', FILENAME ='F:\DATA\SQLGeeksPro_NewName_Data.mdf')
GO
ALTER DATABASE [SQLGeeksPro_NewName] MODIFY FILE (NAME ='SQLGeeksPro_NewName_Log', FILENAME ='F:\DATA\SQLGeeksPro_NewName_Log.ldf')
GO

The message shows that the system catalogs have been updated and new path will be used after the database is started.

Rename Logical and Physical File Name

Step4: Bring up the database using the below query
USE master
GO
ALTER DATABASE [SQLGeeksPro_NewName] SET ONLINE
GO
ALTER DATABASE [SQLGeeksPro_NewName] SET MULTI_USER

Rename Logical and Physical File name

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:

Rename Logical and Physical File Name

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.

Please spread the word:
RSS
Follow by Email
Facebook
Google+
https://sqlgeekspro.com/rename-sql-database-logical-physical-file-names/
Twitter
PINTEREST
LinkedIn

{ Add a Comment }

How To Rename SQL Server Database

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 Name
GO
SELECT DB_NAME() AS DatabaseName, file_id, name AS logical_name, physical_name
FROM sys.database_files
GO 

The Results will be as shown below:

Rename SQL Database

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

Rename SQL Database

 

Step 3: Type in the new name you want for the database

Rename SQL 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
GO
ALTER DATABASE [CurrentDatabaseName] MODIFY NAME = [NewDatabaseName] -- Change the CurrentDatabaseName and NewDatabaseName as required

For Example:
Rename SQL Database

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
GO
EXEC 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:

Rename SQL Database

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

Please spread the word:
RSS
Follow by Email
Facebook
Google+
https://sqlgeekspro.com/rename-sql-server-database/
Twitter
PINTEREST
LinkedIn

{ Add a Comment }

List All Database Users With Permissions

Hi there! In this blog post, we will explore a SQL query that allows you to list all database users with Permissions in SQL Server. As a DBA you must be able to identify which users have access to specific databases and what permissions they possess.

Understanding Database Users and Permissions

Before we dive into the SQL query, first let’s clarify the concepts of database users and permissions.

Database Users:

A database user is an individual or application that interacts with a SQL Server database.
Each user account is mapped to a Windows login or a SQL Server login.
Users are associated with roles and are granted permissions to perform specific actions within the database.

Permissions:

In SQL Server, permissions are used to control access to database objects, such as tables and views. Each user in a database has a set of permissions that determine what they are able to do within the database, such as SELECT, INSERT, UPDATE, DELETE, and EXECUTE.

Query to List All Database Users With Database Role Permissions

USE TestDB  -- Change the db Name
GO
SELECT
       ServerName=@@servername, Dbname=db_name(db_id()),p. name as UserName, 
       p. type_desc as TypeOfLogin, pp. name as DatabaseRoleAssigned, pp. type_desc as TypeOfRole
       FROM sys.database_role_members roles
       JOIN sys.database_principals p ON roles.member_principal_id = p.principal_id
       JOIN sys.database_principals pp ON roles.role_principal_id = pp.principal_id
       WHERE p. type_desc NOT IN('DATABASE_ROLE','ASYMMETRIC_KEY_MAPPED_USER')
       AND p. name NOT IN ('sys','INFORMATION_SCHEMA','guest','dbo')

Output:

List All Database Users Permission

Generally speaking the above output is neat. Point often overlooked is we only got the details of the users which are part of any database roles. In other words I still need to know about users having Execute permission to any Stored Procedure, SELECT/INSERT/UPDATE permission on specific table etc.

Given these points let’s look into the below query.

Query To List All Database Users With Permissions:

USE TestDB  -- Change the db Name
GO
SELECT
   @@servername as SQLInstanceName,
   Dbname=db_name(db_id()),
   u.name as 'UserName',
   u.type_desc as LoginType,
   p.permission_name as 'Permission',
   o.name as 'ObjectName',
   o.type_desc as 'ObjectType'
FROM
sys.database_permissions p
INNER JOIN
sys.objects o ON p.major_id = o.object_id
INNER JOIN
sys.database_principals u ON p.grantee_principal_id = u.principal_id

Output:List All User Permissions

As can be seen in the above example output the query shows the permissions on specific objects. Hence you need these two queries to List All Database Users With Permissions.

Important to realize the following points:
  • The queries returns information about the database roles and permissions on database-level. Therefore it will not return information about server-level permissions.
  • Both the queries returns information about SQL and Windows users but does not include permission of roles. Hence If you want to see the permissions of database roles please feel free to tweak the query.
  • These will only shows the permissions for the specific connected database . Hence to check the permissions for all users in all databases, run the query against each database individually or modify the query. You can refer the link Retrieve all permissions for a user in all user databases which provides assigned database roles for a login in all databases.

Conclusion:

In summary managing permissions in SQL Server is a crucial aspect of database administration. Hence I have provided a simple introduction of users and permissions before diving into the query.
With this in mind, you can easily use the queries to list all database users and their permissions. This will certainly help you maintain a secure and compliant database environment.
Regularly reviewing and auditing permissions is essential to ensure data integrity and security in your SQL Server databases.

Please spread the word:
RSS
Follow by Email
Facebook
Google+
https://sqlgeekspro.com/all-database-users-permissions/
Twitter
PINTEREST
LinkedIn

{ Add a Comment }

The Complete Guide to SQL Server System Databases

Hey there! this is the 3rd article in the category “SQL Server DBA Tutorial: Beginners to Pro”. Here we are going to discuss about SQL Server System databases. The prior article in this series is Understanding SQL Server Versions and Editions

Introduction

To begin with, when you install SQL Server, it creates the system databases automatically. Understanding the role of system databases is crucial. Here we are going to explore everything you need to know about SQL Server system databases,
including their purpose, components, and best practices for managing them.

Table of Contents

  • What are System Databases?
  • Importance of System Databases
  • Understanding the Core System Databases
    • Master
    • Model
    • Msdb
    • Tempdb
    • Resource Database
  • Distribution Database
  • Best Practices to maintain the System Databases

What are System Databases?

System databases are the backbone of a SQL Instance. Each of them play a critical role in the functioning of the database management system. These databases provide critical services to the server and user databases. Each system database has a specific purpose, and they work in harmony.

Importance of System Databases

System databases contain crucial information about the SQL Server instance, including server-level configurations, system objects, and metadata. Understanding the purpose and components of these databases is essential for efficient database management, backup and recovery, and overall system stability.

Understanding the Core System Databases

Now let’s take a deep dive into the core System Databases. The below image shows the system databases when you connect to a SQL Instance.

System Databases

Master Database:

Contains all the system-level information for an instance of SQL Server. The master database is the most important as it is necessary for starting the SQL Server.

This includes instance-wide metadata such as logon accounts, endpoints, linked servers, and system configuration settings.

Also, master is the database that records the existence of all other databases and the location of those database files and records the initialization information for SQL Server. Therefore, SQL Server cannot start if the master database is unavailable.

Model Database:

The model database is used as a template for other databases created in SQL Server, especially when creating user-defined databases.

The entire configuration of the model database, including database options, are copied to the newly created database.

Every time SQL Server is started, it creates tempdb from model hence if model is corrupted, SQL will not come up normally.

Msdb Database: 

The msdb database is used mainly by the SQL Server Agent, and also by other features like SQL Server Management Studio, Service Broker, and Database Mail.

SQL Server automatically maintains a complete online backup-and-restore history within tables in msdb.

Tempdb Database:

TempDB is a global resource that is accessed by all the users in the SQL Server Instance

This stores temporary user objects that you create like temporary tables (Global and Local), temporary variables, temporary stored procedures that hold intermediate results during the sorting or query processing, and cursors.

Internal objects like Work Tables, Work files. Intermediate sort results for operations such as creating or rebuilding indexes.

Version stores, which are collections of data pages that hold the data rows that support features for row versioning.

Resource database:

The Resource Database is a hidden, read-only database that contains system objects, system catalogs, and metadata.

SQL Server system objects, such as sys.objects, are physically persisted in the Resource database, but they logically appear in the sys schema of every database. The Resource database does not contain user data or user metadata.

Microsoft created this database to allow very fast and safe upgrades. You can’t see the database by selecting from sys.databases or
executing sp_helpdb. It also won’t show up in the system databases tree in the Object Explorer pane
of SQL Server Management Studio, and it doesn’t appear in the drop-down list of databases from your query windows.

However, this database still needs disk space.
You can see the files in your default binn directory by using Microsoft Windows Explorer. For Example: C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Binn

mssqlsystemresource.mdf,  and mssqlsystemresource.ldf files.

To explain refer the below screen shot:

System Databases

Distribution Database:

SQL Server creates this database when you configure Replication on SQL Server and you choose the SQL Instance to act as a distributor. It stores replication metadata, history, and the transactions to replicate to other servers.

Best practices to Maintain System Databases:

Create a robust backup strategy for Regular backups of system databases.

Make proper SOP for restoring the system databases so that it is easier in the event of a disaster. Not to mention knowing how to restore system databases is essential for recovering your SQL Server instance.

Managing the size of system databases, especially TempDB, can significantly impact server performance. Hence proper Sizing and Growth Planning is very essential.

Equally important is monitoring solutions to keep an eye on the health and performance of your system databases.

In addition Consider placing system databases on separate disks to prevent contention and optimize performance.

Please spread the word:
RSS
Follow by Email
Facebook
Google+
https://sqlgeekspro.com/sql-server-system-databases/
Twitter
PINTEREST
LinkedIn

{ Add a Comment }

Fix Incorrect Mexico Time in SQL Server sys.time_zone_info

In this article we are going to discuss how to fix incorrect Mexico Time in SQL Server sys.time_zone_info system catalog.

Problem:

One of our customer informed that Mexico changed their DST . In UAT, application is showing correct time which is UTC -6 however in Production the mexico time zone is showing as UTC – 5. The application is referring the sys.time_zone_info system catalog in SQL Server.

Troubleshooting:

In the first place you should understand what is the actual problem. In other words what the customer is talking about. The problem statement it is not very clear if it is SQL Server issue or OS issue or it is something to do with application code.

After a short call with the customer we got to know that as per Mexican Government order published in October 26th, 2022, that Daylight Saving Time (DST) in the United Mexican States will not be observed in 2023 calendar year.

Second is to compare the UAT and Production environment.

  • No change in code at application end.
  • There is no difference in OS time zone settings in application and database server.
  • The result of Mexico Time Zone in sys.time_zone_info were different.

Query to check the Mexico Time Zone information:

SELECT * FROM sys.time_zone_info
WHERE name LIKE '%Mexico%'

Result:

Mexico Time

The above result was from UAT where the output is showing correct. Likewise we checked it in Production environment and result is as follows:

Mexico Time Zone

Certainly we could see the difference as mentioned by the customer. What next?

  • Checked the SQL Server patch and both UAT and Production Instance were in the same patch level
  • Compared the OS patch level on both the servers and we could find the difference in patches installed

Being DBA you need to know how to verify these stuffs to be able to quickly identify the issue. Below screen shot will help you with the path:

Mexico Time Zone

The highlighted patch was not installed in Prod because it was scheduled for next month patching cycle.

A quick read about the patch in the KB article  KB5023702 clarifies the issue:

Mexico Time Zone

Resolution & Conclusion:

The resolution is a no brainer once you find the issue. You have to follow the process as per your organization and get the patch installed in the server.

To conclude incorrect time zone in sys.time_zone_info is not a SQL Server issue. However being DBA you should be able to troubleshoot, find the root cause and suggest the solution. If customer complains about one server shows correct time zone while the other is incorrect without doing any changes in the application end, you should perform a thorough check at server end. The issue occurred because of not having latest OS patch and you can resolve it by going through the relevant article of the OS patch and get it installed.

Please spread the word:
RSS
Follow by Email
Facebook
Google+
https://sqlgeekspro.com/incorrect-mexico-time-sql-server/
Twitter
PINTEREST
LinkedIn

{ Add a Comment }

Query To List All Orphaned Logins In SQL Server

Hi there, being a DBA you must be dealing with orphaned users often but rarely with orphaned logins. In this article I am gonna provide you a script to list all orphaned logins in a SQL Server Instance.

Introduction:

First of all let us understand what are orphaned logins in SQL Server. The logins which does not have access to any database or server roles. Now next question is how orphaned login occurs in SQL Server Instance. In general it happens when you migrate or decommission database(s).

Few of the reasons are mentioned as follows:

  • Migration of database(s) leaving the associated logins.
  • Decommission of database(s) leaving the associated logins.
  • Deleting a server or database role that the login is a member of.
  • Moving user account from one domain to another.

Over time your server can become cluttered with orphaned logins and make it difficult for DBAs to manage. Hence it is important to regularly check and remove them. Obviously you need to follow the process as per your organization.

Query to list all orphaned logins in SQL Server:

DECLARE @dbname VARCHAR(50)  
DECLARE @statement NVARCHAR(MAX)

CREATE TABLE #database_sids
(
    [sid] int NOT NULL
);

DECLARE db_cursor CURSOR 
LOCAL FAST_FORWARD
FOR  
SELECT name
FROM master.sys.databases
WHERE  state_desc='online' 
OPEN db_cursor  
FETCH NEXT FROM db_cursor INTO @dbname  
WHILE @@FETCH_STATUS = 0  
BEGIN

SELECT @statement = 'select sid from ['+@dbname +'].sys.database_principals where sid is not Null and type!=''R'''

INSERT INTO #database_sids ([sid])
EXEC sp_executesql @statement

FETCH NEXT FROM db_cursor INTO @dbname  
END  
CLOSE db_cursor  
DEALLOCATE db_cursor

SELECT sp.name
    , sp.type_desc
FROM sys.server_principals sp
WHERE NOT EXISTS (
    SELECT 1
    FROM #database_sids ds
    WHERE ds. sid = sp. sid
    )
    AND sp.[type_desc] NOT IN (
          N'SERVER_ROLE'
        , N'CERTIFICATE_MAPPED_LOGIN'
        , N'ASYMMETRIC_KEY_MAPPED_LOGIN'
        )
        AND sp.name not in(
       SELECT P.name 
       FROM sys.server_role_members RM
       INNER JOIN sys.server_principals P ON RM.member_principal_id = P.principal_id)

drop table #database_sids

Sample Output:

Orphaned Logins

First thing to remember is not to delete them immediately. As can be seen in the above example, ‘NT AUTHORITY\SYSTEM’. That’s a critical account to verify before deleting. Hence it is important to realize that though the logins are Orphaned you need to do a though check before taking any action.

Conclusion:

In summary orphaned logins can occur due to number of reasons. Primary reasons being database migration, decommission or moving user from one domain to another. Point often overlooked is Orphaned Logins can pose security risk and hinder SQL Server management. However it is possible to identify and address them as per your organization standards. I hope the above script can help in your journey. Please let me know by leaving your comments below.

Please spread the word:
RSS
Follow by Email
Facebook
Google+
https://sqlgeekspro.com/query-to-list-all-orphaned-logins-in-sql-server/
Twitter
PINTEREST
LinkedIn

{ Add a Comment }

Error 15141: The Server Principal Owns One or More Server Roles

Today we are going to discuss about how to resolve the “Error 15141: The Server Principal Owns One or More Server Roles and cannot be dropped”

Introduction

If you are a SQL Server DBA, you may encounter the Error 15141 when trying to delete a login id. First of all let me show you how the error message looks like in SSMS when you try to delete/drop a login.

The Server Principal Owns One or More Server Roles

In the above example screen shot we are trying to delete the login id ‘Admin’. I have observed that some DBA(s) do not read the error message carefully and starts beating about the bush.

There are very similar error messages while dropping logins as you can refer the following links:

Error 15141: The Server Principal Owns One or More Availability Groups

Error 15141: The Server Principal Owns One or More Endpoints

Error 15434: Could not drop login as the user is currently logged in

To emphasize if you observe the above error message clearly reads that the principal (or login) owns one or more server roles, which prevents you from dropping it.

Cause Of the Error 15141: The Server Principal Owns One or More Server Roles

When a server principal or login owns a server role, you cannot drop the login unless you first transfer ownership of the server role to another login. As a matter of fact SQL Server never allows you to drop a login if it owns any object. Hence it throws the error preventing you to drop the server principal or login.

Resolution

To resolve the error, you first need to identify the Server Roles owned by the login or server principal. Then you need to transfer the ownership for each of the server roles to ‘sa’ or any other login as per your organization standard.

1. Query to Identify the Server Roles the Login owns

SELECT sp1.name AS ServerRoleName, 
       sp2.name AS RoleOwnerName
       FROM sys.server_principals AS sp1
       JOIN sys.server_principals As sp2
       ON sp1.owning_principal_id=sp2.principal_id
       WHERE sp2.name='Admin' --Change the login name

Sample Output:

The Server Principal Owns One or More Server Roles

Here in the above example it shows that the login id ‘Admin’ owns two Server roles. On the contrary if the login would have own one or more database role(s), it would allow to delete the login but not the user. Now we’ll change the ownership.

2. Query to Change the Server Role Owner:

USE [master]
GO
ALTER AUTHORIZATION ON SERVER ROLE :: [ServerRole-Test] TO [sa] --Change The ServerRole Name and login Name
GO
ALTER AUTHORIZATION ON SERVER ROLE :: [AnotherServerRole-Test] TO [sa] --Change The ServerRole Name and login Name
GO

3. Drop the Login:

USE [master]
GO
DROP Login [Admin] --change the login Name

Query Result:

The Server Principal Owns One or More Server Roles

As can be seen now the the drop command completed successfully.

Conclusion:

To summarize the error Error 15141: The Server Principal Owns One or More Server Roles and cannot be dropped occurs when the login or server principal owns one or more Server Roles and you are trying to drop the login. Obviously you should not take any knee jerk reaction. After all you are trying to resolve the issue. Hence you should first list out the Server Roles which the login owns. Then change the ownership to [sa] or any other login as per your organization standards. Finally delete or drop the login. Definitely this should resolve the issue. Important to realize that this method will allow you to delete the login even if the login owns and database roles. Hence to repeat you need to be very careful while working in production systems.

Please spread the word:
RSS
Follow by Email
Facebook
Google+
https://sqlgeekspro.com/server-principal-owns-one-or-more-server-roles/
Twitter
PINTEREST
LinkedIn

{ Add a Comment }

Error 15141: The Server Principal Owns One or More Availability Groups

Hey there, this article is about understanding and resolving the error message  “Error 15141: The Server Principal Owns One or More Availability Groups and cannot be dropped”.

Introduction

First of all let me tell you that the above mentioned error occurs when you try to delete a login in a SQL Server Always On Instance. The error message clearly says that the Login Owns an Availability Group(s). In SSMS the error message looks like as shown in the below screen shot.

Error 15141: The Server Principal Owns One or More Availability Groups

Why does the Error 15141: The Server Principal Owns One or More Availability Groups occur in SQL Server?

SQL Server does not allow you to drop any login or Server principal which owns any objects. In this case the server principal is owning an Availability Group. If it allows to drop the login then the Availability Group will become orphaned and that is why SQL Server does not allow to do so.

Now the next question is how come the login has become the owner of the Availability Group.  This is because the login had created the Availability Group while configuring Always On. Does it create any issues as far Always On functionality is concerned? NO, it does not. Then why you need to drop the login?

This is mostly because of the Organization standards. No individual login id should own any Availability Groups. Imagine if the the user leaves the organization and the Id has been removed from Active Directory.

Resolution:

To resolve the error first thing the DBA should do is to identify the list of Availability Groups owned by the login or server principal. Once you have the list, you need to change the ownership to ‘sa’ or any other login as per your Organization Standards. I always say don’t panic and never try to delete the Availability Group itself.

1.Query to Identify the Availability Groups the login Owns:

SELECT ag.[name]  AS availability_groups_name
    ,sp.[name] AS owner_name
    ,ag.group_id
    ,ar.replica_id
    ,ar.owner_sid
FROM  sys.availability_groups ag
JOIN sys.availability_replicas ar ON ag.group_id = ar.group_id
JOIN sys.server_principals sp ON ar.owner_sid = sp.[sid]
WHERE sp.[name]= 'GLOBAL\Dev' -- Change the login name

Sample Output:

Error 15141: The Server Principal Owns One or More Availability Groups

Notably the above output shows that the login ‘GlOBAL\Dev’ owns the Availability Group “DEV-AVG01′. Now we’ll change the owner.

2. Query to Change the Availability Group Owner:

 USE [master]
 GO
 ALTER AUTHORIZATION ON AVAILABILITY GROUP::[DEV-AVG01] TO [sa];
 GO

Now again run the Select query to check the Ownership. Once confirmed you can try dropping the login id.

3. Drop the Login:

 USE [master]
 GO
 DROP LOGIN [GLOBAL\Dev]  --Change the login 
 GO

Summary

To conclude, the Error 15141: The Server Principal Owns One or More Availability Groups occur in SQL Server is one of the common errors DBAs encounter while working on SQL Server Always On Instances. Specifically the error occurs when you try to delete a login or server principal which owns one or more availability Groups. While troubleshooting, first thing to remember is not to take any hasty decision. Particularly in Production. The DBA must first list out the Availability Groups owned by the login and then change the ownership to a different login id as per Organization standards which will resolve the issue.

You can also refer the following articles if you are facing Error 15141: The Server Principal Owns One or More Endpoints 

Or Error 15434: Could not drop login as the user is currently logged in

Please spread the word:
RSS
Follow by Email
Facebook
Google+
https://sqlgeekspro.com/error-15141-the-server-principal-owns-one-or-more-availability-groups/
Twitter
PINTEREST
LinkedIn

{ Add a Comment }

Error 15434: Could not drop login as the user is currently logged in

Hey there, the other day I got a call from a DBA saying he is not able to drop a login from a SQL Instance and getting the following error:
“Error 15434: Could not drop login as the user is currently logged in.”

In this blog post, we will discuss what this error message means, why it occurs and how to resolve it. First of all let’s see how the error message looks like SSMS.

Error 15434: Could not drop login as the user is currently logged in

 

This error message says database administrator tries to drop a login who is doing some work/running transactions in the SQL Server. First thought came to the DBA’s mind is to wait until the login/user disconnects to the database before they can drop it.

Why does Error 15434 occur in SQL Server?

The error occurs because you are trying to delete/drop a login which has a session (Active/Inactive) in the SQL Instance. The SQL server does not allow to drop the login because it would terminate the session. This can cause business impact.

Resolution:

To resolve Error 15434, the database administrator must first identify the connected session and then either wait for the session to be disconnected or manually disconnect the session. Always check with the user if possible. If it is more or like a generic ID like the above example (‘Admin’), it becomes little tricky.

When I got the call, first thing I checked with the DBA if he is trying to delete his own id. This situation may also occur when you Installed SQL Server and added your individual id and as part of the cleaning process you want to delete your id.

Point often overlooked is that you can not delete your own id. In that case you need to connect either using “sa” account or another “security admin” and “processadmin” (to be able to kill the process) or sysadmin account. If you don’t have another such account then ask your fellow DBA(s) to follow the below steps. Obviously SQL Server does not allow to kill your own session.

1. Identify the connected sessions:

 
USE master
GO 
SELECT spid, blocked  AS BlockedBy, loginame  AS LogInName, login_time,
last_batch, status
FROM   sys.sysprocesses
WHERE loginame = 'Admin'   --Change the loginID you are trying to delete

Sample Output:
Error 15434: Could not drop login as the user is currently logged in

Now few points to observe from the sample output. You got few sessions which for the login and they are in sleeping status. You need to to also observe the login_time and the last_batch which is basically the last activity time completed with the connection. If both of them are old, you can decide on killing the sessions. Again be very careful while you do this in production environment.

2. Disconnect or Kill the Sessions:

KILL spid

Screen Shot with above example Spids:
Error 15434: Could not drop login as the user is currently logged in

3. Delete the Login:

DROP Login [loginame]

Error 15434: Could not drop login as the user is currently logged in

As you can see from the above screen shot the login is dropped without any issue/errors.

Summary:

To conclude, the error “Error 15434: Could not drop login as the user is currently logged in” occurs when you try to delete a login having active/inactive connections to the SQL Instance. The database administrator must first identify and disconnect the connected session, and then drop the login.

You can also refer the below articles related to login drop issues:

Error 15141:The Server Principal Owns One or More Endpoints and cannot be Dropped

Error 15141: The Server Principal Owns One or More Availability Groups

Please spread the word:
RSS
Follow by Email
Facebook
Google+
https://sqlgeekspro.com/error-15434-could-not-drop-login-user-is-currently-logged-in/
Twitter
PINTEREST
LinkedIn

{ Add a Comment }