Thursday, December 15, 2005

Test SQL Server Login Permissions With SETUSER

Sometimes you get a request to create a login and you want to test the permissions before letting the user know that he can use the login. you just don't feel like login in and trying to run some SQL statements for every user.
With the SETUSER statement you can eliminate that. Here is some code that explains how to use it

--Create the user
EXEC sp_addlogin 'Albert', 'food', 'pubs'
EXEC sp_adduser 'Albert'

CREATE TABLE dbo.test(id INT identity,datefield DATETIME)

SELECT * FROM test -- as dbo

-- let's run the select as Albert
SETUSER 'Albert'
SELECT * FROM test -- as albert

Now you should get this error
Server: Msg 229, Level 14, State 5, Line 1
SELECT permission denied on object 'test', database 'pubs', owner 'dbo'.

execute just the SETUSER statement and you can drop Albert since the user will be reset to the original user
EXEC sp_dropuser 'Albert'
EXEC sp_droplogin 'Albert'

or close the query window and in another window execute the code below to drop Albert
You have to do this in another window since as Albert you don't have permissions to do this
EXEC sp_dropuser 'Albert'
EXEC sp_droplogin 'Albert'


WesleyB said...

Just a little tip.

I think you can execute it in the same window if you just add a SETUSER without specifying a name before the drop statements.

SQL said...

Yes you are right, I have updated the post


WesleyB said...

No problem.
Keep up the good work!

I've added you to my blogroll ;-)