Search code examples
c#sql-serverauditmulti-user

Get application username for Audit table


I want to implement an audit table and I have no idea how am I supposed to get the username.

I am using C# and Sql Server. I have a Users table in my database. When I log in my windows form application I verify if the correct combination of username and password is used. But how do I inform the database of the current user? I thought of adding an extra column to my Users table in which to set on 1 the logged username. Is that a solution for single-user? But my application in supposed to support multi-user. What could be done in this case?


Solution

  • DECLARE @username varchar(128)
        SET @username = CONVERT(VarChar(128), CONTEXT_INFO());
        PRINT @username
        DECLARE @ID_User int
        SET @ID_User = ( SELECT Users.ID_User
                           FROM Users
                             WHERE Users.Username=@username )
        PRINT @ID_User
    

    This is how I solved it. I inserted this piece of code in each update trigger.