删除用户而不将孤立数据保留在SQL Server中
从SQL Server完全删除用户,而不会留下孤立数据
语境
从登录部分删除用户可以在数据库上创建孤立的用户,因此建议您先删除数据库访问权限,然后再删除用户。
这可能会非常耗时,因此在掌握了各种信息之后,我们想到了下面的代码。
它在删除用户时节省了我的时间,希望对您有所帮助。SQL
DECLARE @UserName SysName='dfgsfdg'--Add Domain if Windows UserSET NOCOUNT ONCREATE TABLE #UserTable(UserName sysname,GroupName sysname,LoginName sysname NULL,DefDBName sysname NULL,DefSchemaName sysname NULL,UserID smallint,SID smallint)CREATE TABLE #Databases(DATABASE_NAME sysname,DATABASE_SIZE INT, REMARKS varchar(254))INSERT INTO #Databases EXEC sp_databasesDECLARE @DBName sysnameDECLARE c1 CURSOR FOR (SELECT DATABASE_NAME FROM #Databases)open c1fetch next from c1 into @DBNameWHILE @@FETCH_STATUS= 0BEGINPRINT @DBNameEXEC ('USE'+ @DBName +' INSERT INTO #UserTable EXEC sp_helpuser') IF (SELECT COUNT(*)FROM #UserTable WHERE UserName=@UserName)>0 BEGIN PRINT'Removing '''+@UserName +''' FROM '+@DBName EXEC ('USE '+ @DBName +' EXEC sp_dropuser '''+@UserName +'''') ENDDELETE FROM #UserTable--ClearTablefetch next from c1 into @DBNameENDCLOSE C1deallocate c1PRINT 'Revoking Login'IF CHARINDEX(@UserName,'\')>1 BEGINEXEC ('EXEC sp_revokelogin '''+ @UserName +'''')--Check string for domain info, assume windows if '/' foundENDIF CHARINDEX(@UserName,'\')=0 AND EXISTS(SELECT * FROM sys.server_principals WHERE name =@UserName) BEGIN--Check if SQL LoginEXEC ('DROP LOGIN ['+ @UserName +']')ENDDROP TABLE #UserTableDROP TABLE #Databases