1. Goal
Delete orphaned users in sql server data.
2. Description
Recently, many of the company's databases are in the cloud, and some of them are in the cloud. There were many problems during this period, and one of the more disgusting problems was "isolated users". When the database is backed up and restored, it is found that the previous user cannot log in. At first I thought that the login account was not created, and then re-created the login account, and then authorized to the database, at this time an error occurred, saying that the user already exists. I just caught my attention and started searching for this information. It turned out that this was caused by notorious isolated users.
Reference: https://developer.aliyun.com/article/725400
Three, query all isolated users on the database server
Use master
Go
Create Table #Orphans
(
RowID int not null primary key identity(1,1) ,
TDBName varchar (100),
UserName varchar (100),
UserSid varbinary(85)
)
SET NOCOUNT ON
DECLARE @DBName sysname, @Qry nvarchar(4000)
SET @Qry = ''
SET @DBName = ''
WHILE @DBName IS NOT NULL
BEGIN
SET @DBName =
(
SELECT MIN(name)
FROM master..sysdatabases
WHERE
/** to exclude named databases add them to the Not In clause **/
name NOT IN
(
'model', 'msdb',
'distribution'
) And
DATABASEPROPERTY(name, 'IsOffline') = 0
AND DATABASEPROPERTY(name, 'IsSuspect') = 0
AND name > @DBName
)
IF @DBName IS NULL BREAK
Set @Qry = 'select ''' + @DBName + ''' as DBName, name AS UserName,
sid AS UserSID from [' + @DBName + ']..sysusers
where issqluser = 1 and (sid is not null and sid <> 0x0)
and suser_sname(sid) is null order by name'
Insert into #Orphans Exec (@Qry)
End
Select * from #Orphans
Fourth, query the isolated account on a specific database
exec sp_change_users_login 'REPORT'
Note: Create a new query on a specific database
Five, delete a specific orphaned account
drop user "xuser1"
Note: Create a new query on a specific database