T-SQL QUERY to Grant Access to Database
You can use SQLCMD mode in SSMS (or SQLCMD itself) to do this.

The following query would connect to an instance, check for the database in question, create the login if it does not exist, and then connect to the database and add a user for that login.

:CONNECT InstanceName
GO
IF EXISTS (SELECT Name FROM sys.databases WHERE name = 'DBName')
    EXEC sp_executeSQL N'   IF NOT EXISTS (SELECT name FROM sys.server_principals WHERE name = ''LOGIN_NAME'')
        CREATE LOGIN LOGIN_NAME FROM WINDOWS;

    USE DBName;
    IF NOT EXISTS (SELECT name FROM sys.database_principals WHERE name = ''LOGIN_NAME'')
        CREATE USER LOGIN_NAME;'
GO


You can do other kinds of variable substitution to make things a little quicker, it's worth reading up at https://docs.microsoft.com/en-us/sql/relational-databases/scripting/edit-sqlcmd-scripts-with-query-editor on the things that you can do.