SQL Server 2005/2008: Identify current user

Torben picture Torben · Apr 9, 2010 · Viewed 8.4k times · Source

I have a web application, which is using a SQL Server 2005 database.

My problem is, that the application has no role management. So the application always accesses the database with one default user. But now I have to save and access a value only for the current user.

Is there any way to do this? Maybe something like a session on the web server? The best way would be, if there is any possibility to access the current session id of the web server from T-SQL.

Do anyone understand my problem? :)

Answer

abatishchev picture abatishchev · Apr 9, 2010

Allows a system-supplied value for the current login to be inserted into a table

DECLARE @sys_usr char(30);
SET @sys_usr = SYSTEM_USER;
SELECT 'The current user is: '+ @sys_usr;
GO

from MSDN

In my opinion, it's better don't do this. Another way: send to stored procedure current user from web sever:

command.CommandText = "EXEC mySP @user";
command.Parameters.Add("@user").Value = ((YourOwnUserClass)Session["user"]).Name;

// or System.Web.HttpContext.Current.User.Identity.Name; to use built-in
// from web page it becomes this.User.Identity.Name;