ProgrammingPope
ProgrammingPope

Reputation: 2237

Is there a way to find out the user that submitted a SQL query?

I am interested in writing a trigger that would ignore queries from a specific SQL user but take action on all others. Is there any way to do this?

A note, though: the user will need to do some queries, so I will need to allow some queries/deletes/etc.

Upvotes: 2

Views: 589

Answers (4)

AllenG
AllenG

Reputation: 8190

How about the built in USER function something like:

If USER <> [your case]
Begin
  Do Stuff
End

Upvotes: 0

HLGEM
HLGEM

Reputation: 96610

If you have a trigger right now that you don't want to fire (we have done this on audit triggers when moving large amounts of data), you can do something like at the start of the trigger:

if (suser_sname() = 'somename') return

If you wanted to do something differnt for just that person you would do something like:

if (suser_sname() = 'somename) 
BEGIN
    some code
END
ELSE
BEGIN
    someother code
END

Note several things about this. Use this code with much caution. First if you can do what you need through security rights, it is a much better choice. Hardcoding someone's name into a trigger can cause strange results at some later time when all have forgotten that you put it in there. If you need to do in the short term (to move 100,000,000 million records in batches over a time into a database without hitting the auidit triggers for example), then don't forget to change it back when the project is done. You don't want to not audit someone's actions forever especially if you are auditing financial transactions. Further, doing something in a trigger will only work for insert/update/delete. You cannot prevent selects from a trigger.

Upvotes: 1

KM.
KM.

Reputation: 103667

try using:

 SELECT SUSER_NAME()

SUSER_NAME (Transact-SQL)

Upvotes: 0

BenTrofatter
BenTrofatter

Reputation: 2158

Just adjust their privileges to not include selects and whatever else you want to prevent them from doing.

Upvotes: 3

Related Questions