Por acaso tenho isso por aí e pode atender às suas necessidades.
Declare
@username sysname,
@password varchar(255),
@SQL nvarchar(max),
@RowsToProcess int,
@CurrentRow int
set @username = 'youruser'
set @password = 'theirpassword'
SET @SQL = 'CREATE LOGIN ' + @username + ' WITH PASSWORD = ''' + @password + ''''
EXECUTE(@SQL);
CREATE TABLE #maintenancetemp (RowID int not null primary key identity(1,1), sqlcmd nvarchar(max) )
insert into #maintenancetemp
SELECT 'USE ' + QUOTENAME(NAME) + ';
IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = N''' + @username + ''') CREATE USER ' + QUOTENAME(@username)
+ ' FOR LOGIN ' + QUOTENAME(@username)
+ ' WITH DEFAULT_SCHEMA=[dbo];
EXEC sys.sp_addrolemember ''db_datareader'',''' + @username + ''';
EXEC sys.sp_addrolemember ''db_datawriter'', ''' + @username + ''''
FROM sys.databases
WHERE database_id > 4
AND state_desc = 'ONLINE'
SET @RowsToProcess=@@ROWCOUNT
SET @CurrentRow=0
WHILE @CurrentRow<@RowsToProcess
BEGIN
SET @CurrentRow=@CurrentRow+1
SELECT @SQL = sqlcmd FROM #maintenancetemp WHERE RowID=@CurrentRow
EXEC SP_EXECUTESQL @SQL
--print @SQL
END
drop table #maintenancetemp
Isso não ajuda com os bancos de dados recém-criados, mas você também pode executar um trabalho noturno para localizá-los:
Declare
@username sysname,
@SQL nvarchar(max),
@RowsToProcess int,
@CurrentRow int
set @username = 'youruser'
CREATE TABLE #maintenancetemp (RowID int not null primary key identity(1,1), sqlcmd nvarchar(max) )
insert into #maintenancetemp
SELECT 'USE ' + QUOTENAME(NAME) + ';
IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = N''' + @username + ''') CREATE USER ' + QUOTENAME(@username)
+ ' FOR LOGIN ' + QUOTENAME(@username)
+ ' WITH DEFAULT_SCHEMA=[dbo];
EXEC sys.sp_addrolemember ''db_datareader'',''' + @username + ''';
EXEC sys.sp_addrolemember ''db_datawriter'', ''' + @username + ''''
FROM sys.databases
WHERE database_id > 4
AND state_desc = 'ONLINE'
AND create_date > dateadd(D, -1, GETDATE())
SELECT @RowsToProcess = COUNT(*) from #maintenancetemp
SET @CurrentRow=0
WHILE @CurrentRow<@RowsToProcess
BEGIN
SET @CurrentRow=@CurrentRow+1
SELECT @SQL = sqlcmd FROM #maintenancetemp WHERE RowID=@CurrentRow
EXEC SP_EXECUTESQL @SQL
END
drop table #maintenancetemp