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

后端 未结 7 723
独厮守ぢ
独厮守ぢ 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:44

    You can use for example Cursor, like this :

    USE master
    GO
    
    DECLARE @DatabaseName VARCHAR(32)   
    DECLARE @SQL NVARCHAR(max)
    DECLARE @User VARCHAR(64)
    SET @User = '[SQL\srvSSISAcc]' --Your User
    
    DECLARE Grant_Permission CURSOR LOCAL FOR
    SELECT name FROM MASTER.dbo.sysdatabases
    WHERE name NOT IN ('master','model','msdb','tempdb')  
    
    OPEN Grant_Permission  
    FETCH NEXT FROM Grant_Permission INTO @DatabaseName  
    WHILE @@FETCH_STATUS = 0  
    BEGIN  
    
        SELECT @SQL = 'USE '+ '[' + @DatabaseName + ']' +'; '+ 'CREATE USER ' + @User + 
        'FOR LOGIN ' + @User + '; EXEC sp_addrolemember N''db_datareader'', 
        ' + @User + '; EXEC sp_addrolemember N''db_datawriter'', ' + @User + ''
    
        EXEC sp_executesql @SQL
        PRINT @SQL
    
    FETCH NEXT FROM Grant_Permission INTO @DatabaseName  
    END  
    CLOSE Grant_Permission  
    DEALLOCATE Grant_Permission 
    

    More info find in my post about this topic: http://www.pigeonsql.com/single-post/2016/12/23/Grant-User-Access-to-All-Databases

提交回复
热议问题