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

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

    I had to tweak Martin Smith's answer slightly as:

    1. The spaces and linebreaks resulted in not all the text being generated properly
    2. The QUOTENAME in the Exec statement put in square brackets which is incorrect.

    My version:

    SET NOCOUNT ON;
    
    DECLARE @user_name    SYSNAME
            , @login_name SYSNAME;
    
    SELECT @user_name = 'HelpdeskUser',
           @login_name = 'Helpdesk'
    
    SELECT 'USE ' + QUOTENAME(NAME) + ';
            CREATE USER ' + QUOTENAME(@user_name)
           + ' FOR LOGIN ' + QUOTENAME(@login_name)
           + ' WITH DEFAULT_SCHEMA=[dbo];
        EXEC sys.sp_addrolemember ''db_datareader'',''' + @user_name + ''';
        EXEC sys.sp_addrolemember ''db_denydatawriter'', ''' + @user_name + '''; 
    GO'
    FROM   sys.databases
    WHERE  database_id > 4
           AND state_desc = 'ONLINE' 
    

    Otherwise works perfectly. Thanks

提交回复
热议问题