Quick! Which specific SQL Server user is logged into which database?

SQL Server's master database stores tables with important and constantly updated information about the state of the SQL server. One of these tables, sysprocesses, can be used to track (in SQL Server itself) which SQL Server users are currently logged in and which database(s) they are accessing.

The quick way to find out if a particular user is accessing a particular table is with a query. The example below checks to see if SQL user syegul is accessing the database BigTable:

select * from master.dbo.sysprocesses
where loginame = 'syegul'
and dbid = db_id('BigTable'))

(Note that the column loginame is spelled just like that, with one n, not two.)

The columns returned from this query

Requires Free Membership to View

allow you to look for numerous criteria for each user connection, such as which protocol the person is using (handy if you want to determine if a user is connecting locally through named pipes or by TCP/IP), what process ID they're attached to and so on. Note that this method will not work if you are abstracting multiple anonymous connections -- for instance, if you are using a Web server front end as the main way to access your data, since everyone will be connecting as the same user.

If you're thinking about writing a trigger for this table that fires whenever a certain user makes a connection or whenever someone accesses a certain table, it won't work -- no, not even if you enable modifications to the system catalogs. It's probably for the best, since one very wise SQL Server administrators' school of thought holds that making such modifications to the master database is a bad idea no matter what the pretext. The best approach to do something like this might be to create a trigger on a given table that fires when a specific type of change is made and then checks the sysprocesses table to see if the user in question is the one making the modification.




This was first published in March 2005

There are Comments. Add yours.


REGISTER or login:

Forgot Password?
Sort by: OldestNewest

Forgot Password?


Your password has been sent to:
