I need to implement the following requirement. I have setup a remote sql server express, certain users shall be able to create databases on remote server and assign other users to have access on it (read,write). Users shall be able to see only the databases created by them or in which they have rights.
First I have created an empty database on remote server => dbo for new database is x, then I've created a different login with:
USE [master]
GO
CREATE LOGIN [username] FROM WINDOWS WITH DEFAULT_DATABASE=[master], DEFAULT_LANGUAGE=[us_english]
Then deny view to any database:
USE master;
GO
DENY VIEW ANY DATABASE TO [username];
Then create new user for login:
USE dbName;
CREATE USER [username] FOR LOGIN [username] ;
GO
Give db owner role:
EXEC sp_addrolemember 'db_owner', [username]
Give permission to see database (here is a little bit tricky because in ssms it can view all the databases but it can have access only on the mapped ones)
USE master GRANT VIEW ANY DATABASE TO [username];
Now on my given database I have 2 users one is username and the other is dbo which is mapped on the user that created the database and is different form username.
After that I'm using SMO to transfer this databases from remote server to localhost and while executing transferDatabase.TransferData();
I'm getting the following error "The login already has an account under a different user name." When I create the transfer instance I set also the property CopyAllUsers= true.
How can I fix this?
I've found out that if i make the following changes
USE [master]
GO
CREATE LOGIN [username] FROM WINDOWS WITH DEFAULT_DATABASE=[master], DEFAULT_LANGUAGE=[us_english]
Then deny view to any database:
USE master;
GO
DENY VIEW ANY DATABASE TO [username];
USE master;
GO
ALTER AUTHORIZATION ON DATABASE::Dinesh TO [username];
GO
Now username sees in ssms only the databases on which is mapped and the transfer will probably work. But now I cannot distinguish between the first creator of the database and the recently granted user. For one database I should grant dbowner permissions to more than one user.
So if then I create another login and I execute:
USE master;
GO
ALTER AUTHORIZATION ON DATABASE::dbName TO [anotherUser];
GO
Now username can not access the database.