CONTEXT_INFO
is fixed-length binary(128)
rather than varbinary(128)
. The parsing error is due to the trailing binary zeros being evaluated.
Instead of CONTEXT_INFO
, consider using SESSION_CONTEXT
(available in SQL Server 2016 onwards). SESSION_CONTEXT
allows one to store one or more key/value pairs with a sysname
key type (nvarchar(128)
) and a value of type sql_variant
with sp_set_session_context
. The value can be retrieved with the SESSION_CONTEXT
function.
So if your underlying objective is to store and retrieve the User, Log, and Culture values, you could create SESSION_CONTEXT
entries for the 3 values instead of XML
:
EXEC sp_set_session_context @key= N'User', @value= 'system';
EXEC sp_set_session_context @key= N'Log', @value= 1;
EXEC sp_set_session_context @key= N'Culture', @value= 1;
SELECT SESSION_CONTEXT(N'User'), SESSION_CONTEXT(N'Log'), SESSION_CONTEXT(N'Culture');
You could alternatively use XML similarly to your original attempt but, since XML
is not a permitted sql_variant
type, you'll need to add the XML
value as varchar/nvarchar and CAST
to XML
:
DECLARE @xml XML = '<row User="system" Log="1" Culture="1"/>';
DECLARE @xmlVarchar varchar(8000) = CAST(@xml AS varchar(8000));
EXEC sp_set_session_context @key= N'xml', @value= @xmlVarchar;
SELECT CAST(CAST(SESSION_CONTEXT(N'xml') AS varchar(8000)) AS xml);