Skip to main content

Posts

Showing posts from June, 2021

Fix SQL database User accounts when doing a backup and restore.

-- select the desired database to fix the user accounts --Use ; EXEC sp_change_users_login 'report'--See all orphaned users in the database. DECLARE @OrphanedUsers TABLE ( IndexKey Int IDENTITY(1,1) PRIMARY KEY, UserName SysName,--nVarChar(128) UserSID VarBinary(85) ) INSERT INTO @OrphanedUsers EXEC sp_change_users_login 'report' DECLARE @CRLF as nVarChar SET @CRLF = CHAR(10) + '&' + CHAR(13)--NOTE: Carriage-Return/Line-Feed will only appear in PRINT statements, not SELECT statements. DECLARE @Sql as nVarChar(MAX) SET @Sql = N'' DECLARE @IndexKey as Int SET @IndexKey = 1 DECLARE @MaxIndexKey as Int SET @MaxIndexKey = (SELECT COUNT(*) FROM @OrphanedUsers) DECLARE @Count as Int SET @Count = 0 DECLARE @UsersFixed as nVarChar(MAX) SET @UsersFixed = N'' DECLARE @UserName as SysName--This is an orphaned Database user. WHILE (@IndexKey <= @MaxIndexKey) BEGIN SET @UserName = (SELECT UserName FROM @Or