I am currently using the CONTEXT_INFO property of the Master database for storing the logged in username to use it later in Table Triggers for auditing.
While migrating to SQL Azure, the issue of Cross-Database connections popped and I couldn’t find direct solutions to this issue.
Following are the Issue Details:
- I call Stored Procedure XXX from Data Access Layer and pass the Username as Parameter
- The username is used to set the CONTEXT_INFO value in XXX
- The CONTEXT_INFO value is then used in Tables Insert/Update/Delete Triggers to Store Username for Application Auditing
Solutions that I found so far:
- Create Table In Database to work as CONTEXT_INFO
- Use 2 Connection Strings in Data Access Layer, one for Master Database (to set CONTEXT_INFO) and the other is for the application and execute the SET CONTEXT_INFO each time before opening the connection to my application
But I find both solutions risky, specially when expanding the Database over multiple SQL Azure Databases in the future.
Appreciate your support.
The approach I took is shown below. On trick was to check to see running not running on SQL Azure, then we would need to call ‘SET CONTEXT_INFO …’. This allows the same code to be execute on local SQL Server Express and Azure without changes.
Create a table to store the context info (not in master but in the same database)
Create a stored procedure to ‘Set Context Info’ which is called from application
Create a stored procedure to ‘Get Context Info’
In trigger source, use:
Now you have the username stored in the table variable. In case changes are applied by an administrator outside of your application, you may also want to check if the username was not set and default to something like *SYSTEM_USER*.