Identify Schema for table depending on User Access - sql

I have a scenario where there are two database
schemas: Schema1 and Schema2 and a table: Table1.
Same Table1 exisits in both the schemas like Schema1.Table1 and Schema2.Table1.
Now we have some stored procedures which will be in another Schema say Schema3.
CREATE PROCEDURE SCHEMA3.GETDETAILS (
#AS_CODE_TYPE VARCHAR(1) ,
#AS_OUT_FIELD1 VARCHAR(50) OUT ,
#AS_RETURN_VAL INTEGER OUT
)
AS
BEGIN
SELECT #AS_OUT_FIELD1 = [EXTERNALREFKEY] FROM TABLE1 WHERE CODE_TYPE = #AS_CODE_TYPE
IF #AS_OUT_FIELD1 <> ' '
BEGIN
SET #AS_RETURN_VAL = 1 ;
END
ELSE
BEGIN
SET #AS_RETURN_VAL = - 1 ;
END
END
Now My question:
How do i get the schema details for a given user .
Do i need to modify the SP to dynamically append the schema to table depending on the user access to a specific schema.
Please help

When creating a user, if you don't specify it's schema, it will has the default schema 'dbo'.
You can get the user schema by running the bellow query in master DB:
USE master;
SELECT s.name user, s.default_schema_name user_schema FROM sys.database_principals s
WHERE s.name='user'
GO
For example:
You also can alter the user schema if you have the permission.
For more details, Changing the default schema of a user:
ALTER USER Mary51 WITH DEFAULT_SCHEMA = Purchasing;
GO
Hope this helps

Related

Cross Database Trigger with EXECUTE AS not working - permission problem

I have 2 Databases. Database A belongs to an ERP System and Database B is my own database.
I've created an AFTER INSERT DML Trigger in a table which belongs to Database A.
Every single ERP User is associated with a DB User.
At the moment I copy all the users from Database A to Database B to grant permission for my tables.
It was the only solution I could find to make it work but it's bad because a new ERP User will get an Error Message when there's no user in Database B.
So now I tried it once again to use WITH EXECUTE AS .... I tried OWNER and different DB users but nothing works and I have absolutely no idea what's wrong.
I even granted all permissions for the user on the tables I use in the trigger.
Let's say I have a user called "triggerUser" when I do WITH EXECUTE AS 'triggerUser' it doesn't work but when I remove the EXECUTE AS .... and use the triggerUser for the ERP Login it works so the user got the permissions to write my tables.
Here's my trigger. Maybe you have an idea what I'm missing.
CREATE TRIGGER [dbo].[TR_manAddAutomatikQueueForLager_AfterInsert]
ON [SL_MWAWI].[dbo].[LAGERPROTOKOLL]
WITH EXECUTE AS 'moep'
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON
DECLARE #Mandant int
SET #Mandant = (SELECT MANDANT_ID FROM SL_Daten.dbo.MANDANT WHERE Datenbankname = 'SL_MWAWI')
-- insert
IF EXISTS (SELECT * FROM inserted) AND NOT EXISTS(SELECT * FROM deleted)
BEGIN
INSERT INTO maniacSellerGen2.dbo.manAutomatikQueue
SELECT #Mandant, ISNULL(wsa.WebShopId, wsav.WebShopId), ISNULL(wsav.VaterArtikelnummer, wsa.Artikelnummer), 'Lager', GETDATE()
FROM inserted
LEFT JOIN maniacSellerGen2.dbo.manWebShopArtikel wsa
ON wsa.Artikelnummer COLLATE DATABASE_DEFAULT = inserted.Artikelnummer COLLATE DATABASE_DEFAULT
AND #Mandant = wsa.Mandant
LEFT JOIN maniacSellerGen2.dbo.manWebShopArtikelVarianten wsav
ON wsav.Artikelnummer COLLATE DATABASE_DEFAULT = inserted.Artikelnummer COLLATE DATABASE_DEFAULT
AND #Mandant = wsav.Mandant
WHERE ((wsa.Artikelnummer IS NULL AND wsav.Artikelnummer IS NOT NULL)
OR (wsa.Artikelnummer IS NOT NULL AND wsav.Artikelnummer IS NULL))
END
END
Here's a screenshot from the permissions for the user in every database it has db_datareader and db_datawriter.
Permissions
I also did tried this:
GRANT INSERT ON dbo.manAutomatikQueue TO moep
GRANT DELETE ON dbo.manAutomatikQueue TO moep
GRANT UPDATE ON dbo.manAutomatikQueue TO moep
GRANT SELECT ON dbo.manAutomatikQueue TO moep
Thanks a lot!

Access Master DB Tables from User Database in SQL AZURE

I am trying to access sys.SQL_Logins on Master DB from a User Database so that I could join sys.sql_logins with sys.sysusers.
UserDatabase
SELECT DP.NAME, DP.sid, SU.sid
FROM sys.sql_logins DP
INNER JOIN SYS.sysusers SU
ON DP.name=SU.name
In Azure I am not able to do this, since I am not able to call master DB from UserDatbase. My objective was to compare SID of sys.sql_logins with sys.sqlusers from User Database.
Is there any way I could join these two tables in Azure.
You can only execute queries against a single database. However, you can set up an external table to point to the master database views. This code should get you there:
CREATE MASTER KEY; -- if your DB doesn't already have one
GO
CREATE DATABASE SCOPED CREDENTIAL AccessToMaster
WITH IDENTITY = 'yourmasterlogin', SECRET = 'yourpassword'; --TODO set a login name and password that can access the master database
GO
CREATE EXTERNAL DATA SOURCE MasterDatabase
WITH
(
TYPE = RDBMS,
LOCATION = N'yourserver.database.windows.net', --TODO replace your server name
DATABASE_NAME = N'master',
CREDENTIAL = AccessToMaster
);
GO
CREATE SCHEMA MasterDB AUTHORIZATION dbo;
GO
CREATE EXTERNAL TABLE MasterDB.sql_logins
(
[name] sysname,
principal_id int,
[sid] varbinary(85),
[is_disabled] bit
)
WITH
(
DATA_SOURCE = MasterDatabase,
SCHEMA_NAME = 'sys',
OBJECT_NAME = 'sql_logins'
);
GO
SELECT * FROM MasterDB.sql_logins;
GO

Find all databases where particular user exists and its role

I have a huge instance containing 1000+ databases. I need to find a way to query entire instance and find databases that contain particular user and what role this user has. I am not interested whether the user is orphanded. I just want to know which databases have this user and which do not.
Lets say that my user is called TestUser. Databases that do not contain this user should return NULL.
I would like the results in the following format:
Column1 - Database Name
Column2 - UserName (if exists or else NULL)
Column3 - UserRole (if exists or else NULL)
Under the assumption that you are not looking for issuing 1000+ selects, one (extremely ugly) solution would be:
SELECT 'DB_1' , UserName , UserRole
FROM DB_1.UsersTable
WHERE Username = 'TestUser'
UNION
SELECT 'DB_2' , UserName , UserRole
FROM DB_2.UsersTable
WHERE Username = 'TestUser'
:
:
Another solution is to use DYNAMIC SQL:
Collect the list of all the DBs that you to check,
Build a string hosting a select statement like the one above,
Execute the statement.
Again, both methods are shameful.
create table #temp
(
dbname sysname,
dbrole sysname,
dbuser sysname
)
Exec sp_msforeachdb '
if db_id()>4
Begin
insert into #temp
select db_name(), rp.name as database_role, mp.name as database_user
from sys.database_role_members drm
join sys.database_principals rp on (drm.role_principal_id = rp.principal_id)
join sys.database_principals mp on (drm.member_principal_id = mp.principal_id)
End
'
The Roles Part is referenced from here:
Get list of all database users with specified role

Changes to sysusers and sysxlogins in SQL 2008

I am currently updating a MS SQL 2000 server to SQL 2008. One of the issues highlighted by the Upgrade advisor is that the undocumented table sysxlogins has been removed.
I currently have a procedure that is run by a user 'foo' to determine if the user 'bar' exists in the database blah. If the user exists the user's password is compared to the password that was passed in to the procedure in order to determine if bar is allowed to log in to an application, it looks like this:
#UserName Varchar(50),
#Password Varchar(50)
As
Set NoCount On
------------------------------------------------------------------------------------
-- Check username
------------------------------------------------------------------------------------
If Exists
(
select top 1 name
from blah.dbo.sysusers With (NoLock)
where name = #UserName
)
Begin
------------------------------------------------------------------------------------
-- Check Password
------------------------------------------------------------------------------------
If Not Exists
(
Select *
From master.dbo.sysxlogins With (NoLock)
Where srvid IS NULL
And name = #Username
And ( ((#Password is null) or (#Password = '') and password is null)
Or (pwdcompare(#Password, password, (CASE WHEN xstatus&2048 = 2048 THEN 1 ELSE 0 END)) = 1))
)
Begin
Return 2
End
Else
Begin
------------------------------------------------------------------------------------
-- Check Role
------------------------------------------------------------------------------------
Select usg.name
From blah.dbo.sysusers usu
left outer join (blah.dbo.sysmembers mem inner join blah.dbo.sysusers usg on mem.groupuid = usg.uid) on usu.uid = mem.memberuid
left outer join syslogins lo on usu.sid = lo.sid
where usu.name = #Username
and usg.name not like 'db_%'
Return 0 -- Username and password correct
End
End
Else
Begin
Return 1 -- Username incorrect
End
This all works fine under SQL 2000, yet I must now pay the price of using undocumented system tables and make it work under 2008.
There are two problems with this, the first problem is that foo can no longer see all of the database users when executing:
select * from blah.dbo.sysusers
or Microsoft's recommended alternative:
select * from blah.sys.database_principals
I understand that this is due to the fact that members of the public role no longer have access to object meta data unless they are a member of sysadmin or have the View Definition permission on the object.
It is not possible for foo to be a member of sysadmin, so as far as I understand I need to grant foo the View Definition permission, but on which object? I don't think I do it on the system view, so do I do it on every single user?
Secondly, and similarly, I need to change my reference to sysxlogins to sys.sql_logins. Again foo can only see itself and sa when executing
select * from sys.sql_logins
How can I get foo to see all of the server logins in this list?
There will no doubt be similar problems when accessing sysmembers and syslogins later on in the code but hopefully an understanding of the two examples above will help me to sort the rest out.
Thanks in advance,
You can grant the SELECT right directly on sys.database_principals, as long as the login has a user in the master database. For example:
use master
create user MyUser for login MyUser
grant select on sys.database_principals to MyUser
Then, in SQL Server 2008, passwords are encrypted, even for the administrator. You can, however, verify a password by trying to change it. The change procedure will give an error if the old password is incorrect.
declare #rc int
begin try
exec #rc = sp_password 'welcome', 'welcome', 'MyUser'
end try
begin catch
set #rc = ERROR_NUMBER()
end catch
-- Should be 0 on success
select #rc
For this to work, you have to disable Enforce password policy in the Login Properties dialog. Otherwise, the policy would prevent you from changing your password too often.
I think GRANT SELECT ON... is more troublesome as one have to add the user to the master database. The below was the solution for me:
USE master
GRANT VIEW ANY DEFINITION TO foo
If you have an app that works on various versions of SQL you need to check if the server version is higher then 8 (GRANT VIEW ANY DEFINITION works from SQL 2005 though it seemes not be needed there).

How do I determine if a database role exists in SQL Server?

I'm trying to figure out how I can check if a database role exists in SQL Server. I want to do something like this:
if not exists (select 1 from sometable where rolename='role')
begin
CREATE ROLE role
AUTHORIZATION MyUser;
end
What table/proc should I use here?
SELECT DATABASE_PRINCIPAL_ID('role')
--or
IF DATABASE_PRINCIPAL_ID('role') IS NULL
USER_ID is deprecated and could break. CREATE ROLE indicates SQL 2005+ so it's OK
if not exists (select 1 from sys.database_principals where name='role' and Type = 'R')
begin
CREATE ROLE role
AUTHORIZATION MyUser;
end