HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Add users to multiple databases

Submitted by: @import:stackexchange-dba··
0
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 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:

$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.