SQL - Impersonate SYSTEM_USER - sql

Is there a way to impersonate or change the SYSTEM_USER on MS SQL 2005?
I have many views (written by a third party) which I can not change which references an SYSTEM_USER to "ID Table".
... AND idCode = SUBSTRING(SYSTEM_USER, CHARINDEX('\', SYSTEM_USER) + 1, LEN(SYSTEM_USER))
*I do have rights to the tables that the views pull from, BUT these views have the added SYSTEM_USER.*
Thanks.

Check out the Execute As Transact SQL
Providing you have the correct permissions you can execute any T-SQL as another user and then revert back to the original connection credentials.
Select System_User
Go
Execute As Login = 'SomeOtherLogin'
Select System_User
Revert
Go
Select System_User
Go
This will output the current connection credentials for the first and third select and output the specified credentials for the second select.

Related

Escape wildcard, *, in sp_addsrvrolemember

Is it possible to escape a wildcard * in the below stored procedure?
exec sp_addsrvrolemember '*Everyone-Group', 'sysadmin'
I need the script to identify * but not as a wildcard, but rather as an asterisk.
Thank you for your help.
Okay so I reached out to a SQL expert to educate me and here is what I needed:
CREATE LOGIN [_Everyone-Group] FROM WINDOWS WITH DEFAULT_DATABASE=[master]
GO
ALTER SERVER ROLE sysadmin ADD MEMBER [_Everyone-Group]
As for my misunderstandings:
The * is only considered a wildcard in MS Access, not SQL like it was mentioned in this post
The line of code "ALTER SERVER ROLE" assumes the login is already existing in the master database, I had thought it would look for it and add it in (because of ADD MEMBER) and then also apply 'sysadmin' permissions.
I did not know the _ was needed instead of * in the brace.

SQL Server User Mapping Error 15023

I try to map my other DB to a user by going to Security > Logins > right click someuser > Properties > User Mapping > Select DB > set as db_owner and then ok, but I keep on getting an error saying
User, group, or role 'someuser' already exists in the current database. (Microsoft SQL Server, Error: 15023)
What is causing the error, and how do I map that user to the database?
To fix the user and login mapping you need to open a query window in the SQL Server Management Studio. Enter the following two lines and replace myDB with the database name and myUser with the correct user name:
USE myDB
EXEC sp_change_users_login 'Auto_Fix', 'myUser'
If run successfully you should get an output like this one:
The row for user '****' will be fixed by updating its login link to a login already in existence.
The number of orphaned users fixed by updating users was 1.
The number of orphaned users fixed by adding new logins and then updating users was 0.**
Your user should now be mapped correctly.
Edit:
New way to Resolve/Fix an Orphaned User:
In the master database, use the CREATE LOGIN statement with the SID option to recreate a missing login, providing the SID of the database user.
CREATE LOGIN <login_name>
WITH PASSWORD = '<use_a_strong_password_here>',
SID = <SID>;
To map an orphaned user to a login which already exists in master, execute the ALTER USER statement in the user database, specifying the login name.
ALTER USER <user_name> WITH Login = <login_name>;
When you recreate a missing login, the user can access the database using the password provided. Then the user can alter the password of the login account by using the ALTER LOGIN statement.
ALTER LOGIN <login_name> WITH PASSWORD = '<enterStrongPasswordHere>';
if it is just one or two users, then easiest way is to drop the database user from the restored database, remap the database user to the server login using SSMS. If the server login does not exist then just create it, map the user.
Option 2: If you are migrating a large number of users, use sp_help_revlogin. sp_help_revlogin is a Microsoft supplied stored procedure that will help migrate logins from one server to another, including passwords and SIDs. Here is a good article about it SP_HELP_REVLOGIN : http://www.databasejournal.com/features/mssql/article.php/2228611/Migrating-Logins-from-One-SQL-Server-to-Another.htm
Code patches to help use it :
run following T-SQL Query in Query Analyzer. This will return all the existing users in database in result pan.
USE YourDB
GO
EXEC sp_change_users_login 'Report'
GO
Run following T-SQL Query in Query Analyzer to associate login with the username. ‘Auto_Fix’ attribute will create the user in SQL Server instance if it does not exist. In following example ‘ColdFusion’ is UserName, ‘cf’ is Password. Auto-Fix links a user entry in the sysusers table in the current database to a login of the same name in sysxlogins.
USE YourDB
GO
EXEC sp_change_users_login 'Auto_Fix', 'ColdFusion', NULL, 'cf'
GO
Run following T-SQL Query in Query Analyzer to associate login with the username. ‘Update_One’ links the specified user in the current database to login. login must already exist. user and login must be specified. password must be NULL or not specified
USE YourDB
GO
EXEC sp_change_users_login 'update_one', 'ColdFusion', 'ColdFusion'
GO
2) If login account has permission to drop other users, run following T-SQL in Query Analyzer. This will drop the user.
USE YourDB
GO
EXEC sp_dropuser 'ColdFusion'
GO
Create the same user again in the database without any error.
If you assign permissions to a database user without mapping it to the database first, it throws the error you mentioned.
You should be able to delete the user, map it to the database and then assign the user to the db_owner role.
First drop your user, then execute the script below:
USE [YOURDB]
GO
CREATE USER [USERNAME] FOR LOGIN [USERNAME]
GO
USE [YOURDB]
GO
ALTER USER [USERNAME] WITH DEFAULT_SCHEMA=[dbo]
GO
I had the problem when I was trying to copy a production database to a local test database. In SSMS, I made sure to disconnect from the production server before executing scripts on the local. However, even though I thought I had disconnected, someone pointed out that the title of the production database was still there, and I got errors that objects were already there. The solution was to totally exit from SSMS and start it again, only connecting to the local test database that time.
you can solve problem by expand database ->Security -> Users
and delete the user 'someuser' ,after that go to user mapping and assign.
this problem happen some times because the database user 'someuser' was deleted from 'Logins' in Security section in SSMS and the database still own this user
Create failed for User (Microsoft.SqlServer.Smo)
SQL Server Error User, group, or role already exists in the current database. (Microsoft SQL Server, Error: 15023)
To fix above error delete user under each database individually

CREATE USER in Dynamic SQL on SQL Azure

I want to write a stored procedure that checks the environment a database resides in (Based on the name) and creates the appropriate user and role for our application.
This would allow us to automate setting up permissions if we move a database between environments (Currently due to the limitations of Windows Azure SQL Database we have to manually run a script which is not ideal and prone to human error).
So the syntax we are using is:
DECLARE #UserToAdd VARCHAR(50) = (
SELECT CASE
WHEN #Environment = 'Development' THEN 'DevelopmentApplicationUser'
WHEN #Environment = 'Test' THEN 'TestingApplicationUser'
ELSE ''
END
)
IF (#UserToAdd != '')
BEGIN
EXEC ('CREATE USER [' + #UserToAdd + '] FOR LOGIN [' + #UserToAdd + '];')
EXEC ('EXEC sp_addrolemember N''WebUser'', N''' + #UserToAdd + ''';')
END
This works correctly on our development server (SQL Server 2008 R2) but in Windows Azure SQL Database we get the below error:
The CREATE USER statement must be the only statement in the batch
Now the MSDN documentation does state:
If the CREATE USER statement is the only statement in a SQL batch, Windows Azure SQL Database supports the FOR | FROM LOGIN clause. If the CREATE USER statement is not the only statement in a SQL batch or is executed in dynamic SQL, the FOR | FROM LOGIN clause is not supported.
However this means that we cannot automate our permissions whatsoever.
Has anyone got around this issue and been able to produce dynamic sql that creates a user? Alternatively is there a way around this in a stored procedure?
I opened a support case with Microsoft to see if this is possible and the response was that if you want to check the existence of a login or a user and then create that login or user, you MUST use separate connections for the check and then the creation. It is NOT possible to check and create if not exists in the same transaction or batch. In Sql Azure.
Hth,
Oli
I speak under correction here.
you can create the user without FOR LOGIN
then use sp_change_users_login to map the user to a login after the fact

SQL Server - Permission on a per table basis?

I have a .net where I only have read access to the SQL Server database. Is it possible for SQL Server to give me write access to just ONE of the tables in the database, and restrict me to read only for the rest of the database?
Use this TSQL script, if you need:
EXEC sp_addrolemember N'db_datareader', N'User1';
GRANT INSERT, UPDATE, SELECT ON
MyTable
TO User1 --for multiples, it's TO User1,User2
In SQL Server Management Studio, right-click the read-only user in database name|security|Users and select Properties.
Select "Securables" and click "Search...". In the popup select "All objects of the type..." and click OK. Select "Tables" in the next window and click OK.
Then back in the Securables window, for each table that the user may write to:
Click on the table, and in the Permissions window underneath, in the "Grant" column, select "Insert", "Select" and "Update".
Yes, yes it is.
Just grant yourself the ReadOnly role and give yourself explicit write permissions to the table in question.

t-sql create user and grant execute on permission for stored procedures

I have a script which creates a database, stored procs, views, tables, udf. I want to include a script to create a user 'user_1' and give execute permission on the database.
I tried following to create grant exec command for all stored procs
declare #permission varchar(max)
select #permission = COALESCE(
#permission + '; ' + 'Grant Execute on ' + name + ' user_1',
'Grant Execute on ' + name + ' user_1')
from sysobjects where xtype in ('P')
exec (#permission)
But exec (#permission) does not work. It gives
incorrect syntax near ';'.
How can I solve this?
Create Login: creates the server level login. Then...
Create User: lets the Login account attach to your database. Then...
Grant Execute To: grants execute rights to ALL of the sp's and functions in your db. Use "Grant Execute ON abc TO xyz" if you only want to grant rights to specific sps.
Create login abacadaba with password='ABVDe12341234';
Create user abacadaba for login abacadaba;
Grant Execute to abacadaba;
Have you tried:
CREATE LOGIN TestUser WITH PASSWORD = 'TopSecret'
GRANT EXEC ON MyStoredProc TO TestUser
you can also "CREATE USER" if that's what you want.
Had exactly the same problem as original user, but for me it was bad characters embedded in the TSQL - I'm guessing from whatever source it was cut and pasted from.
Anyway depending on how much whitespace you have, just delete the whitespace between the words and replace with regular spaces.
Try all the other answers before this, it's fairly unlikely - I'm only adding it as it was so frustrating having 2 lines of TSQL that looked identical above/below each other, but resulted in different result messages when highlighted and run in Management Studio...
UPDATE: The bad characters were pasted from Microsoft Lync