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)
INSERT INTO test
SELECT GETDATE()
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
SETUSER
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'
Just a little tip.
ReplyDeleteI think you can execute it in the same window if you just add a SETUSER without specifying a name before the drop statements.
Yes you are right, I have updated the post
ReplyDeleteThanks
No problem.
ReplyDeleteKeep up the good work!
I've added you to my blogroll ;-)