SET CONTEXT_INFO (Transact-SQL)
Applies To: SQL Server 2014, SQL Server 2016 Preview
Topic Status: Some information in this topic is preview and subject to change in future releases. Preview information describes new features or changes to existing features in Microsoft SQL Server 2016 Community Technology Preview 2 (CTP2).
Associates up to 128 bytes of binary information with the current session or connection.
Applies to: SQL Server (SQL Server 2008 through current version).
The preferred way to retrieve the context information for the current session is to use the CONTEXT_INFO function. Session context information is also stored in the context_info columns in the following system views:
SET CONTEXT_INFO cannot be specified in a user-defined function. You cannot supply a null value to SET CONTEXT_INFO because the views holding the values do not allow for null values.
SET CONTEXT_INFO does not accept expressions other than constants or variable names. To set the context information to the result of a function call, you must first include the result of the function call in a binary or varbinary variable.
When you issue SET CONTEXT_INFO in a stored procedure or trigger, unlike in other SET statements, the new value set for the context information persists after the stored procedure or trigger is completed.
A. Setting context information by using a constant
The following example demonstrates SET CONTEXT_INFO by setting the value and displaying the results. Note that querying sys.dm_exec_sessions requires SELECT and VIEW SERVER STATE permissions, whereas using the CONTEXT_INFO function does not.
SET CONTEXT_INFO 0x01010101; GO SELECT context_info FROM sys.dm_exec_sessions WHERE session_id = @@SPID; GO
B. Setting context information by using a function
The following example demonstrates using the output of a function to set the context value, where the value from the function must be first placed in a binary variable.
DECLARE @BinVar varbinary(128); SET @BinVar = CAST(REPLICATE( 0x20, 128 ) AS varbinary(128) ); SET CONTEXT_INFO @BinVar; SELECT CONTEXT_INFO() AS MyContextInfo; GO