Help with query

Since this is a one-time execution, do you really need to check? If this is going to be included in a build script - then checking would be appropriate.

If you do need to check, then you will need to go with dynamic SQL. Here is a sample:

    Use master;
     If Not Exists (Select * From sys.server_principals sp Where sp.name = 'DOMAIN\otheruser')
  Begin
Declare @sqlCommand nvarchar(max) = 'Create Login [DOMAIN\otheruser] From Windows With default_database = master';
Execute sp_executeSQL @sqlCommand;
    End
     Go
     
    Use msdb;
     If Not Exists (Select * From sys.database_principals dp Where dp.name = 'DOMAIN\otheruser')
  Begin
Declare @sqlCommand nvarchar(max) = 'Create User [DOMAIN\otheruser] With default_schema = dbo';
Execute sp_executeSQL @sqlCommand;
    End

  Alter Role SQLAgentOperatorRole Add Member [DOMAIN\otheruser];

 --==== Any additional permissions
--       Grant Select On ... To [DOMAIN\otheruser];
1 Like