3

I have an Azure database and I have created another one on the same server. After that, I have created a user and a corresponding login (see the script below) with the intention to use it for the second database only. After running the script I have googled (below), the second user can access both databases. How to deny the second user access to the first database? There are DENY and REVOKE, that deny specific rights, but it is not obvious to me which one should be used.

Bonus question: was it possible to create a user that can access the second database only?

IF NOT EXISTS (SELECT 1 FROM master.sys.databases WHERE ('[' + name + ']' = '[Elmah5]'))
    CREATE DATABASE Elmah5;
GO

IF NOT EXISTS (SELECT 1 FROM sys.sql_logins  WHERE name = 'ElmahAdmin')
    CREATE LOGIN ElmahAdmin WITH PASSWORD = ''
GO

IF NOT EXISTS (SELECT 1 FROM sys.database_principals  WHERE name = 'ElmahAdmin')
    CREATE USER ElmahAdmin FOR LOGIN ElmahAdmin WITH DEFAULT_SCHEMA=[dbo]
GO

enter image description here


HOW IT SHOULD HAVE BEEN DONE

  1. Connect using your primary account.
  2. Switch your current database to MASTER (circled in, just type in MASTER and hit ENTER) and run

    IF NOT EXISTS (SELECT 1 FROM master.sys.databases WHERE ('[' + name + ']' = '[SecondDB]'))
        CREATE DATABASE SecondDB;
    GO  
    IF NOT EXISTS (SELECT 1 FROM sys.sql_logins  WHERE name = 'SecondDBAdmin')
        CREATE LOGIN SecondDBAdmin WITH PASSWORD = ''
    GO
    

enter image description here

  1. Still under your first login, switch to SecondDB and run

    CREATE USER SecondDBAdmin FOR LOGIN SecondDBAdmin WITH DEFAULT_SCHEMA=[dbo]
    GO
    EXEC sp_addrolemember @rolename = 'db_owner', @membername = 'SecondDBAdmin'
    GO
    

enter image description here

  • Instead of editing the answer into your question you should consider a self answer. – Erik Jan 8 '16 at 16:34
4

If you don't want the user to have access to the database at all make sure your user does not have system administrator privileges which would allow them access to every database. Baring that, on the database you don't want the 2nd user to have access to, run the following:

USE [1stDatabase]
DROP USER [2ndUser]
GO

To create an exclusive user for the second database:

USE MASTER
CREATE LOGIN [login_name here] WITH PASSWORD = '[password here]'
GO

USE [2ndDatabase]
CREATE USER [login name here] FOR LOGIN [login name here]
GO
  • Use [dbname] does not work on Azure, but I was able to solve my problem thanks to your help, see above. – Yulia V Jan 8 '16 at 16:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.