recreate user with schema - sql-server

Following code recreates a user:
-- Remove link to order schema
ALTER AUTHORIZATION ON SCHEMA::order TO dbo
-- Recreate order user without login
DROP USER order
CREATE USER order WITH DEFAULT_SCHEMA = order
-- Restore link to order schema
ALTER AUTHORIZATION ON SCHEMA::order TO order
My question is, why do we need to remove link to schema before dropping a user, and restore it back after user created?

The behavior of Schemas changed in SQL Server 2005. Schemas are no longer equivalent to database users; each schema is now a distinct namespace that exists independently of the database user who created it. In other words, a schema is simply a container of objects. A schema can be owned by any user, and its ownership is transferable.
https://msdn.microsoft.com/en-us/library/ms190387.aspx
http://basitaalishan.com/2014/05/29/the-database-principal-owns-a-schema-in-the-database-and-cannot-be-dropped/

Ok, just found why we need to temporary move the schema link to another owner before deleting a user.
It will return error if not doing so:
The database principal owns a schema in the database, and cannot be dropped.

Related

Objects being created as DBO for all users in SQL Server application

We have Windows Authentication on our SQL Server Databases.
Every object gets created as dbo which I don't mind. But we are unable to track who created what? Can someone help on how it can be managed so we can at least track who is doing what? The login names from the trace is also generic
login name - ABC\gMSA_SQL$
If I login to the server with my windows authentication and run the below command select SUSER_NAME(), I can see my username and not a generic one. So now if I create a table where can I get this username from?
The default schema of the user are set to dbo. It could be due to many reasons, as mentioned in the below msdn reference
The default schema will be the first schema that will be searched by
the server when it resolves the names of objects for this database
user. Unless otherwise specified, the default schema will be the owner
of objects created by this database user.
If the user has a default schema, that default schema will used. If
the user does not have a default schema, but the user is a member of a
group that has a default schema, the default schema of the group will
be used. If the user does not have a default schema, and is a member
of more than one group, the default schema for the user will be that
of the Windows group with the lowest principal_id and an explicitly
set default schema. (It is not possible to explicitly select one of
the available default schemas as the preferred schema.) If no default
schema can be determined for a user, the dbo schema will be used.
DEFAULT_SCHEMA can be set before the schema that it points to is
created.
DEFAULT_SCHEMA cannot be specified when you are creating a user mapped
to a certificate, or an asymmetric key.
The value of DEFAULT_SCHEMA is ignored if the user is a member of the
sysadmin fixed server role. All members of the sysadmin fixed server
role have a default schema of dbo.
You can find out the default schema of the users by running the below query. Refer to sys.database_principals
SELECT default_schema_name FROM sys.database_principals
If you want to restrict the users to only create objects on their schema, you have to do below things:
CREATE SCHEMA [userPrincipalSchema];
GO
CREATE USER [userPrincipal]
WITH PASSWORD='SUPERCOMPLEXPASSWORDHERE'
, DEFAULT_SCHEMA=[userPrincipalSchema]
GO
DENY ALTER ON SCHEMA::[dbo] to [userPrincipal]
GO
ALTER AUTHORIZATION ON SCHEMA::[userPrincipalSchema] to [userPrincipal];
GO
GRANT CREATE TABLE, CREATE VIEW, CREATE PROCEDURE TO [userPrincipal];
GO
This way, you can ensure that the [userPrincpal] is able to create objects only on their schema and you can track, the objects created by them.

Exclusive User ownership on sql server tables

Requirement: User who created tables in a particular schema, should own the tables, other users who got access to that schema should not able to perform any action on that table(including read).
Example:
Tables created by ‘User1’ in ‘Schema1’ should be exclusive to the User1 only with (SELECT, CREATE, UPDATE and DELETE)
Other Users who got access to ‘Schema1’, should not able to perform any actions on the tables created by ‘User1’
This requirement is expected to be available for users who have access to the 'schema1', so the tables they create is accessible only for them and not for other users.
For the sake of the discussion let's CREATE new LOGIN, new SCHEMA, and new USER.
use master
GO
CREATE LOGIN SO_Login WITH PASSWORD = 'Dont1Use2This3In4Production'
GO
Use AdventureWorks2019
GO
CREATE SCHEMA SO_Schema
GO
CREATE USER SO_User FOR LOGIN SO_Login;
GO
In theory, you could get what you are looking for, by simply have a rule which allows CREATE TABLE on specific schema. Something like: GRANT CREATE TABLE ON SCHEMA::SO_Schema TO public;
In this case we could give everyone the option to CREATE TABLE on the schema and use simple DDL trigger on CREATE TABLE in order to add permissions like SELECT,DELETE,INSERT,UPDATE for the user that created the table.
unfortunately, GRANT CREATE TABLE ON SCHEMA is not supported.
To CREATE TABLE you Required to have CREATE TABLE permission in the database and ALTER permission on the SCHEMA in which the table is being created.
https://learn.microsoft.com/en-us/sql/t-sql/statements/create-table-transact-sql?view=sql-server-ver15#permissions-1
This makes the task more complex and probably not recommended in most cases since you will need to provide more permissions than what you really want the USER to have...
If you still want to get this work (against the recommendation) then you will need to GRANT ALTER ON SCHEMA and GRANT CREATE TABLE on database to all - all means "public"
use AdventureWorks2019
GO
GRANT ALTER ON SCHEMA::SO_Schema TO public;
GO
GRANT CREATE TABLE TO public;
GO
next, you will need to DENY the unwonted permission since the above will give all USERs a lot more power than you want to!
This can be done by CREATE DDL TRIGGER on the DATABASE for any DDL_DATABASE_LEVEL_EVENTS
https://learn.microsoft.com/en-us/sql/relational-databases/triggers/ddl-event-groups?view=sql-server-ver15
inside the TRIGGER you should check what was the event. If it was something else than CREATE_SCHEMA or the USER that executed the event should not CREATE SCHEMA then you ROLLBACK TRANSACTION;.
Note! Since you do not want to change the trigger each time a new USER need to CREATE TABLE and add the USER name to the hard coded list of users which can CREATE TABLE, it is best to CREATE new ROLE and simply add each USER you need to this ROLE
CREATE ROLE ModifyTable;
GO
In this case that you based on a ROLE like above ModifyTable, you can GRANT ALTER ON SCHEMA and GRANT CREATE TABLE only to the ROLE ModifyTable instead of to public
In addition, in the same TRIGGER if the USER is one of these that should be able to CREATE the table then you should GRAND him permission to INSERT, DELETE, UPDATE, SELECT on the table which he just created.
Remember that if you forget to DENY a permission from this USER or all the rest then you might have a security issue - which is why this is not recommended procedure.
Your best option is to re-0design the system so you will not need this exact recruitment. So... you can do it as I explained here, but it is not recommended for most cases.
A much better approach is NOT to permit USERs to CREATE TABLEs except for these you can trust with all tables. You should CREATE THE TABLEs for your users directly or using application which you control, and give them the permission to use the specific table which they need. ALTER SCHEMA is not recommended permission to give to simple users!
A user with ALTER permission on a schema can create procedures, synonyms, and views that are owned by the schema's owner. Those objects will have access (via ownership chaining) to information in other schemas owned by the schema's owner. When possible, you should avoid granting ALTER permission on a schema if the schema's owner also owns other schemas.
https://learn.microsoft.com/en-us/sql/t-sql/statements/grant-schema-permissions-transact-sql?view=sql-server-ver15

How can I delete a user from sql server 2012 who owns a schema

I created a new user in Sql Server 2012 and "by accident" I marked them as owner of multiple schemas. I meant to mark them as members of the schema but I was on the wrong tab!
Because they are now owners of the schema I can't unselect the ownership and I can't delete the user either. How can I undo my mistake?
You must transfer ownership of the schema to some other user, probably dbo, prior to removing the user:
To test this, I did the following:
Create a user to own the schema, and a test schema:
USE tempdb;
CREATE USER [testuser] WITHOUT LOGIN;
GO
CREATE SCHEMA [max] AUTHORIZATION testuser;
GO
Try to drop the user, which will fail:
DROP USER [testuser];
GO
Msg 15138, Level 16, State 1, Line 1
The database principal owns a schema in the database, and cannot be dropped.
Transfer ownership of the schema to some other user, in this case the special user, dbo, which owns the database:
ALTER AUTHORIZATION ON SCHEMA::[max] TO dbo;
GO
Now, drop the test user, which works:
DROP USER [testuser];

Sql Server Schemas, one private area per person, but have read access to others

I have a requirement for a database that is effectively a "play" area for people creating stats data for themselves and shared with others.
I have a read only database full of core data. All users have read access.
I want a second "play" database where 'n' people can query the "core" database and create there own tables, Sp's etc. I want these users to have a schema each. I want everything they create to be added to their schema by default unless they specify it explicitly (ie [dbo]) in the script. I want them all to be able to collaborate and be able to read data (and look at sp's) from other users schema but not add objects or execute sps' in the others users schema.
These users use 2014 management studio to run these queries. They all authenticate using Integrated Security (windows).
Can this be done?
I tried setting default schema on a user but by default when they add a table it goes to [dbo] because the property grid in 2014MS defaults to [dbo] and you have to edit it. If they just enter "create table Table1" I want it to go into their schema
I tried making the user the owner of the schema. I tried setting public to have select access to these user schemas. But something is not right!
I would have thought this was a common setup where developers get their own schema within a single database. Or, is it always the case that separate DB's are used to achieve this? I am sure others would appreciate a short script that sets this up for a couple of users :)
SQL Server admin is not my main area, so any guidance would be appreciated
For a test user User1, you can create a schema UserSchema1 and do the following
I want a second "play" database where 'n' people can query the "core" database
you can make the user part of the db_datareader role like this
USE [CoreDatabase]
GO
exec sp_addrolemember db_datareader, 'User1'
I want everything they create to be added to their schema by default
Create the schema and add appropriate permissions
USE [PlayDatabase]
GO
CREATE SCHEMA [UserSchema1] AUTHORIZATION dbo;
GO
GRANT ALTER, DELETE, EXECUTE, INSERT, REFERENCES, SELECT, UPDATE, VIEW DEFINITION ON SCHEMA::UserSchema1 TO User1;
GRANT CREATE TABLE, CREATE PROCEDURE, CREATE FUNCTION, CREATE VIEW TO User1;
Make the schema default for the user
ALTER USER [User1] WITH DEFAULT_SCHEMA=[UserSchema1]
For more info refer this thread
https://dba.stackexchange.com/questions/21733/allow-user-to-do-anything-within-his-own-schema-but-not-create-or-drop-the-schem
I want them all to be able to collaborate and be able to read data (and look at sp's) from other users schema but not add objects or execute sps' in the others users schema.
Allow user to view definition of other user's objects and do SELECT's on play database
USE [PlayDatabase]
GO
GRANT VIEW Definition TO [User1]
GO
exec sp_addrolemember db_datareader, 'User1'

sql server 2008 r2 - deny create and drop database but allow everything else

I want to create a new user 'user1' that will be able to see all databases and all tables and also execute SQL statement, procedures etc.
The only thing that I want to deny is creating/dropping or change database (rename, change properties, create new database or drop existing database).
How can I do it?
If it is a dev server, I find it easiest to create a role in MODEL database that has all the right mix of privileges and then assign that role to a user mapped to a login that you need. When you create a new database that user will automatically be assigned privileges to that database.
Two caveats here: that login must be present on the server or else you will not be able to create a new database. Another important one is that the user will have completely unnecessary privileges to read and write to model database by default - definitely NOT a good idea on a production server. On a production server just create the role in model database, but only create user for the databases that you need.
This is the script you can use to create the role:
USE [model]
GO
CREATE ROLE [db_data_read_write_execute] AUTHORIZATION [db_securityadmin]
GO
ALTER ROLE [db_datareader] ADD MEMBER [db_data_read_write_execute]
GRANT EXECUTE to [db_data_read_write_execute]
GO
CREATE USER [DML_Only_User] FOR LOGIN [DML_Only_User_Login] WITH DEFAULT_SCHEMA=[dbo]
GO
ALTER ROLE [db_data_read_write_execute] ADD MEMBER [DML_Only_User]

Resources