How do i add a User to a Database that is in an always on Availability group? - sql

i have a an always on availability group with one database called Mydb, 1 Primary Replica - MyReplica1 and 1 secondary - MyReplica2 in Async Commit. It is also a readable secondary.
I want to add a new login and map it as DBO in the database Mydb.
Creating the login and mapping in MyReplica1 is fine with no issues.
Creating Login on MyReplica2 is fine but i cannot map it or create the user as i get the error below
Failed to update database "Mydb" because the database is read only. (Microsoft SQL Server, Error: 3906)
Any thoughts on how i can go about this without having to failover to the Secondary just to create the Login.

Related

Creating a non-ORACLE_MAINTAINED user in ORACLE XE 18 via JDBC

I want to create a user from JDBC (if possible) in an ORACLE Express database. That user can't have the ORACLE_MAINTAINED flag in the DBA_USERS view.
Trying CREATE USER newuser IDENTIFIED BY xxx, but it throws a ORA-65096: invalid common user or role name. To avoid it, I had to set the flag ALTER SESSION SET "_ORACLE_SCRIPT"=TRUE, as other posts recommend. But that way, it's marked as ORACLE_MAINTAINED.
I'm connecting to the xe default database.
Context:
I'm working with the Oracle Docker image; it's for integration testing purposes. The metadata queries the app uses exclude ORACLE_MAINTAINED='Y' users/tables, and I'm not able to list them (not working with data, just metadata). I could remove the WHERE from the queries, but I would prefer to avoid it, and keep the app queries untouched.
Thanks!

How to create a contained database and user in azure sql

I am trying to create a contained user for just one database in Azure SQL Server,
I have tried using the sp_configure keyword, it says it is not available in the version of the SQL Server I am using.
Also, I used the Alter database statement, I got the error below:
ALTER DATABASE statement failed; this functionality is not available
in the current edition of SQL Server.
Please, how can I solve this problem???
You do not need to run the ALTER DATABASE ... SET CONTAINMENT command on Azure SQL DBs to accept contained users - it is already enabled by default. You simply need to create the user with just a login and password. A simple example of a contained user with password:
CREATE USER yourUser WITH PASSWORD = 'yourPassword';
See the official documentation for more examples:
https://learn.microsoft.com/en-us/sql/t-sql/statements/create-user-transact-sql?view=sql-server-ver15#e-creating-a-contained-database-user-with-password
https://learn.microsoft.com/en-us/sql/t-sql/statements/create-user-transact-sql?view=sql-server-ver15#f-creating-a-contained-database-user-for-a-domain-login
sp_configure is not supported in Azure SQL database, even use the Alter database:
In Azure SQL database, login is used to login the Azure SQL server, user is to connect to the database. User is database level, and login is server level.
Create login in master DB(( Login must be created in master DB)):
CREATE LOGIN AbolrousHazem
WITH PASSWORD = '340$Uuxwp7Mcxo7Khy';
Then we can create user in user DB( create the database contained user in user DB):
CREATE USER AbolrousHazem FOR LOGIN AbolrousHazem;
GO
For more details, please ref: https://learn.microsoft.com/en-us/azure/azure-sql/database/logins-create-manage

Is it possible to add a user with login to readonly database?

I have a sql azure database which is geo-replicated. Now I want to create a user with login and grant him a permission to read data from some table in the readonly replica.
But it seems like it's not possible.
When I'm trying to create a user for login I get a error message about readonly database:
CREATE USER [user_name] FOR LOGIN [login_name]
Failed to update database "test-master" because the database is
read-only.
When I'm trying to make a database read-write it tells me that it's not possible because of geo-replication:
ALTER DATABASE [test-master] SET READ_WRITE
ODBC error: State: 42000: Error: 1468 Message:'[Microsoft][ODBC Driver 17 for SQL
Server][SQL Server]The operation cannot be performed on database
"test-master" because it is involved in a database mirroring session
or an availability group. Some operations are not allowed on a
database that is participating in a database mirroring session or in
an availability group.'. Msg 5069, Level 16, State 3, Line 5 ALTER
DATABASE statement failed.
So is it possible at all?
UPDATE:
It's seems like login info is not replicated.
Script User as CREATE TO in Master db:
CREATE USER [user_name] FOR LOGIN [login_name] WITH DEFAULT_SCHEMA=[dbo]
Script User as CREATE TO in Replica db:
CREATE USER [user_name] WITH DEFAULT_SCHEMA=[dbo]
Does it mean that it's not possible to add a new login to the replica db?
I found a solution here: https://blogs.msdn.microsoft.com/azuresqldbsupport/2018/05/21/tips-tricks-what-you-need-to-do-to-creat-sql-login-to-authenticate-to-azure-sql-dbs-members-in-auto-failover-group/
It's possible to use Forced Failover feature which swap databases and hence make my replica writable so I can create a user and grant permissions(of course during this change previous master db becomes readonly).

Restore database SQL server query

I want a way to write my own query to restore the database. The database to restore needs to have all the settings to delete the current user and re-map the same user. The reason for that is because when the database is restored, the user will not have the right settings to use the database and will have to re assign the user the privileges.
Check this out:-
Step 1: Retrive the Logical file name of the database from backup.
RESTORE FILELISTONLY
FROM DISK = 'D:BackUpYourBaackUpFile.bak'
GO
Step 2: Use the values in the LogicalName Column in following Step.
----Make Database to single user Mode
ALTER DATABASE YourDB
SET SINGLE_USER WITH
ROLLBACK IMMEDIATE
----Restore Database
RESTORE DATABASE YourDB
FROM DISK = 'D:BackUpYourBaackUpFile.bak'
WITH MOVE 'YourMDFLogicalName' TO 'D:DataYourMDFFile.mdf',
MOVE 'YourLDFLogicalName' TO 'D:DataYourLDFFile.ldf'
/If there is no error in statement before database will be in multiuser
mode.
If error occurs please execute following command it will convert
database in multi user./
ALTER DATABASE YourDB SET MULTI_USER
GO
The reason for that is because when the database is restored, the user will not have the right settings to use the database and will have to re assign the user the privileges.
I guess that:
You are using mixed mode authentication and the user is a SQL Server user (not a Windows user)
You are restoring the database to a different server than the one where the backup was made
Correct?
If yes, you need to consider the following:
The user must exist on the second server as well, it's not created automatically when you restore the database there
It's not enough to just create a new user with the same name on the second server - to SQL Server, this would be a different user!
I guess that the second point is the reason why your user doesn't have "the right settings" after restoring.
Some background:
Internally, all SQL Server users are represented by a SID (something unique and unreadable - similar to a GUID. SQL Server doesn't care about the actual user name internally).
The permissions that each user has on a database are saved inside the database, using the SID and not the username
When you restore the database to a different server, the permissions are restored with the database...but they only work when there's a user with the exact SID on the new server
As I said before: when you just create a new user with the same name, he gets a new SID.
So what probably happened is this:
on the old server, there's a user "Mohammed Tahir" with the SID 123456789
inside the database, there's a permission that says "SID 123456789 is allowed to read from this database"
you restored the database on the new server
you created a user "Mohammed Tahir" on the new server, but he has a different SID (let's say 987654321), so the existing permissions on 123456789 don't work for him!
So what you need is a way to "copy" the user from the old server to the new server, with the exact same SID.
There is a stored procedure from Microsoft named sp_help_revlogin, which does just that.
It generates a script with all the users from the old server. You can then run the script on the new server, and it will create the users with the same SIDs they had on the old server.
Then, you can restore the database from the old server to the new server, and all the permissions already in the database just work.
You can get sp_help_revlogin from this MSDN article:
How to transfer logins and passwords between instances of SQL Server.
Note that there is nothing special about the actual restoring process - it's the users and their SIDs that make the difference.
So you don't need any "special" commands to restore the database, just the standard ones, for example the one from Rahul Tripathi's answer.

Need to learn how to set appropriate permissions on SQL Server database to allow Synchronisation through Sync Framework 2.1

SQL Server is not my strong point and I start to get lost when going past the basic Create Table, Select from Table etc.
I am attempting to set up a database synchronisation scenario with an Microsoft SQLCompact 3.5 database being Synced through a Proxy to and SQL 2008 R2 database. It is being synced through the Microsoft Sync Framework 2.1.
I got everything set up and working fine through the proxy when the user account is the db_owner of the database.
Of course this now needs to be locked down - so I have been trying to restrict the permissions to the bare minimum required for Synchronisation.
According to the Microsoft articles, I need to do the following...
Use the principle of least permission. Do not grant more permissions than are required to perform a specific task. For example, do not grant INSERT permissions for server database tables that are involved in download-only synchronization. Synchronization operations require the following permissions:
EXECUTE permissions on all the stored procedures that Sync Framework uses to read and write to metadata tables and base tables.
SELECT, INSERT, UPDATE, and DELETE permissions for metadata tables and any base tables that will be updated during a synchronization session.
When you provision SQL Server databases that use SqlSyncProvider, be aware of the following permissions requirements for provisioning:
CREATE TABLE permissions to enable creation of the metadata tables: scope_info and scope_config, and the tracking tables that are created for each base table.
ALTER TABLE to add triggers to the base tables.
CREATE PROCEDURE permissions to create the procedures that Sync Framework requires.
SELECT and INSERT permissions for scope_info and scope_config tables.
SELECT permissions for base tables.
I allowed the wizards in Visual Studio 2010 to create the Sync database and proxy for me.
As such - I am unable to find the scope_info and scope_config tables in SQL Server databases, and I am also unable to find the metadata tables so cannot set permissions on these tables. Also - where would I find the stored procedures that the Synchronisation framework is trying to use - I have looked but cannto find them.
Where would I find these and how would I go about setting the appropriate permissions?
I have granted datareader and datawriter, Insert, Update, Delete and Select as well as Execute permissions on the SQL Server database but the sync fails. I have also granted Create Table, Create Procedure and ALTER permissions on the database for the user as well- but still it fails.
If i enable the db_owner role for the user - it works.
The error I receive is:
Unable to initialize the client database, because the schema for table 'tblApplications, tblApplicationConfiguration, tblApplicationInstallProperties, tblApplicationPreRequisites, tblApplicationTypes, tblComputerApps, tblComputers, tblComputerTypes, tblDriveHWSerials, tblDrives, tblDriveTypes, tblFunctions, tblLocationApps, tblLocationComputers, tblLocationIPAddress, tblLocations, tblLocationUsers, tblPermissions, tblRegionLocations, tblRegions, tblRegisteredModules, tblRequestFormats, tblRequestStatus, tblRequestTypes, tblRoles, tblRoleUsers, tblSecurity, tblUsers, tblVehicle, tblVehicleLocationMap, tblVehicleMake, tblRequestProcessingStatus, tblDriveStatus, tblVideoViewTypes' could not be retrieved by the GetSchema() method of DbServerSyncProvider.
Make sure that you can establish a connection to the client database and that either the SelectIncrementalInsertsCommand property or the SelectIncrementalUpdatesCommand property of the SyncAdapter is specified correctly.
I am not able to use the db_owner role when its released.
there are two types of database providers in Sync Framework, the offline provider (SqlCeClientSyncProvider/DbServerSyncProvider) which is used by the Local Database Cache project item and the collaboration/peer-to-peer provider (SqlSyncProvider/SqlCeSyncProvider).
the offline providers dont use the scope_xxx tables as such you wont find it.
assuming you used the default SQL Server Change Tracking when you configured the sync via the wizard, try granting VIEW CHANGE TRACKING permission to the account you're using to connect to the database.
I'm not sure if it will help, but I found this:
Try to set UploadOnly on the SyncTable object instead. When you set it on the SyncAdapterBuidler, the select incremental commands are not generated by the builder. These commands are used to get the table schema from the database. Since these are missing you are getting the schema error.
Also, maybe this blog entry will help.
As JuneT Mentioned, you should turn on Change Tracking
ALTER DATABASE YourDataBaseName
SET CHANGE_TRACKING = ON
(CHANGE_RETENTION = 2 DAYS, AUTO_CLEANUP = ON)