patternsqlMinor
Add users to multiple databases
Viewed 0 times
multipleusersdatabasesadd
Problem
I have 980 DBs on 1 server and I am supposed to grant readonly access to a couple of users.
I certainly don't want to run
I don't know if
Can someone let me know if something else can be done?
I certainly don't want to run
alter DB add user... statement since it is definitely time consuming. I don't know if
exec sp_addrolemember 'db_datareader', 'user' works? Can someone let me know if something else can be done?
Solution
Here's how I would do it in Powershell:
This assumes the login foo has already been created. It also assumes running on the localhost instance.
$instance = 'localhost'
$dbs = dir SQLSERVER:\SQL\$instance\DEFAULT\Databases
$sql = 'CREATE USER [foo] FROM LOGIN [foo]; ALTER ROLE db_datareader ADD MEMBER [foo];'
$dbs | ForEach-Object {Invoke-Sqlcmd -ServerInstance $instance -Database $_.Name -Query $sql}This assumes the login foo has already been created. It also assumes running on the localhost instance.
Code Snippets
$instance = 'localhost'
$dbs = dir SQLSERVER:\SQL\$instance\DEFAULT\Databases
$sql = 'CREATE USER [foo] FROM LOGIN [foo]; ALTER ROLE db_datareader ADD MEMBER [foo];'
$dbs | ForEach-Object {Invoke-Sqlcmd -ServerInstance $instance -Database $_.Name -Query $sql}Context
StackExchange Database Administrators Q#120628, answer score: 9
Revisions (0)
No revisions yet.