Skip to end of banner
Go to start of banner

Code for multiple databases

Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

Version 1 Next »

DECLARE @Domain nVARCHAR(MAX) = 'icon'
DECLARE @User nVARCHAR(MAX) = 'synsdtnonprod'

-- Create the login and grant it sysadmin server role
EXEC ('USE [master]; CREATE LOGIN ['+@Domain+'\'+@User+'] FROM WINDOWS WITH DEFAULT_DATABASE=[master]')
EXEC ('USE [master]; ALTER SERVER ROLE [sysadmin] ADD MEMBER ['+@Domain+'\'+@User+']')

-- Get a list of all databases
DECLARE @Databases TABLE (DatabaseName nVARCHAR(MAX));
INSERT INTO @Databases (DatabaseName)
SELECT name
FROM sys.databases;

-- Loop through each database
DECLARE @Database nVARCHAR(MAX);
WHILE EXISTS (SELECT 1 FROM @Databases)
BEGIN
    SELECT TOP 1 @Database = DatabaseName FROM @Databases;

    -- Create the user in the current database and grant db_owner role
    BEGIN TRY
        EXEC ('USE [' + @Database + ']; CREATE USER ['+@Domain+'\'+@User+'] FOR LOGIN ['+@Domain+'\'+@User+']')
        EXEC ('USE [' + @Database + ']; ALTER ROLE [db_owner] ADD MEMBER ['+@Domain+'\'+@User+']')
    END TRY
    BEGIN CATCH
        -- Handle any errors, e.g., print an error message
        PRINT 'Error creating user in database ' + @Database + ': ' + ERROR_MESSAGE();
    END CATCH

    -- Remove the processed database from the list
    DELETE TOP (1) FROM @Databases;
END

-- Grant permissions in msdb
EXEC ('USE [msdb]; CREATE USER ['+@Domain+'\'+@User+'] FOR LOGIN ['+@Domain+'\'+@User+']')
EXEC ('USE [msdb]; ALTER ROLE [db_owner] ADD MEMBER ['+@Domain+'\'+@User+']')
  • No labels