Fix Msg 8116 “Argument data type varchar is invalid for argument 1 of session_context function” in SQL Server

If you’re getting SQL Server error Msg 8116 with the message Argument data type varchar is invalid for argument 1 of session_context function, it’s because you’re passing the wrong data type to a function – in this case the SESSION_CONTEXT() function.

This can happen if you pass a string literal to the SESSION_CONTEXT() function without prefixing it with the N character.

The same error (Msg 8116) can also occur in other contexts – it’s not limited to the SESSION_CONTEXT() function. For example, you could get the same error when using the SUBSTRING() function.

Example of the Error

Here’s an example of code that produces the error:

EXEC sp_set_session_context 
    @key = 'language', 
    @value = 'English'; 
SELECT SESSION_CONTEXT('language');

Result:

Msg 8116, Level 16, State 1, Line 4
Argument data type varchar is invalid for argument 1 of session_context function.

Here, I passed a string as the first argument to SESSION_CONTEXT(), but I didn’t prefix it with N.

The argument provided to SESSION_CONTEXT() is the key of the value being retrieved. It must be of type sysname. This is basically the same as nvarchar(128) NOT NULL, which means you need to prefix the string literal with the N character.

The same error (Msg 8116) can occur in many other contexts – it’s not limited to the SESSION_CONTEXT() function.

Either way, it means that you’re passing the wrong data type to the function.

Solution

To solve the above issue, all we need to do is prefix the key with the N character:

EXEC sp_set_session_context 
    @key = 'language', 
    @value = 'English'; 
SELECT SESSION_CONTEXT(N'language');

Result:

English

Problem solved. All I did with change 'language' to N'language'.

As mentioned, error 8116 isn’t limited to the SESSION_CONTEXT() function. Either way, the solution is the same – ensure that the argument is of a data type that the function accepts.