SQL Server - How to Grant Read Access to ALL databases to a Login?

后端 未结 7 731
独厮守ぢ
独厮守ぢ 2021-02-05 05:22

I need to give a new login read access to all 300 databases on a server. How can I accomplish this without checking 300 checkboxes in the user mapping area?

7条回答
  •  旧巷少年郎
    2021-02-05 05:48

    Declare @Databases Cursor
    Declare @DbName as nvarchar(64)
    Declare @Sql nvarchar(max)
    Declare @BaseAddUserSql nvarchar(max)
    Declare @BaseAddRoleSql nvarchar(max)
    
    Set @Databases = Cursor Fast_Forward For
        select [name]
        from master..sysdatabases
        where [name] not in('master','model','msdb','tempdb')
    
    Open @Databases
    Fetch Next From @Databases Into @DbName
    
    Set @BaseAddUserSql = 'exec sp_adduser ''LOGINNAME'''
    Set @BaseAddRoleSql = 'exec sp_addrolemember ''db_datareader'', ''LOGINNAME'''
    
    
    While @@Fetch_Status = 0
    Begin
        Begin Try
            Set @Sql = 'Use ' + Quotename(@DbName)
            exec (@Sql)
    
            Set @Sql = Replace(@BaseAddUserSql, 'LOGINNAME', )
            exec(@Sql)
    
            Set @Sql = Replace(@BaseAddRoleSql, 'LOGINNAME', )
            exec(@Sql)
        End Try
        Begin Catch
        End Catch
    
        Fetch Next From @Databases Into @DbName
    End
    
    Close @Databases
    Deallocate @Databases
    

提交回复
热议问题