SQL Server - Give a Login Permission for Read Access to All Existing and Future Databases

后端 未结 2 1251
礼貌的吻别
礼貌的吻别 2020-12-19 04:48

I have a stored procedure that finds all the existing databases and reads from a table in each one.

Is there a way I can give a login read access to all databases,

2条回答
  •  抹茶落季
    2020-12-19 05:19

    For new databases, add the user in the model database. This is used as the template for all new databases.

    USE model
    CREATE USER ... FROM LOGIN...
    EXEC sp_addrolemember 'db_datareader', '...'
    

    For existing databases, use sp_MSForEachDb

    EXEC sp_MSForEachDb '
     USE ?
     CREATE USER ... FROM LOGIN...  
     EXEC sp_addrolemember ''db_datareader'', ''...''
    '
    

提交回复
热议问题