Wednesday, 23 September 2015

MSSQL Context_Info session value global value.

How to store and read bits from a session value called Context_Info.



SET Context_Info 0xFF; -- bitindex is the value of the bit you want to get for example 7 is a value of 64 or 0x40 -- CONVERT(tinyint,bitindex value) & SUBSTRING(Context_Info(),byteoffset+1, 1) select CONVERT(tinyint,0x01) & SUBSTRING(Context_Info(),1,1) AS '1', CONVERT(tinyint,0x02) & SUBSTRING(Context_Info(),1,1) AS '2', CONVERT(tinyint,0x04) & SUBSTRING(Context_Info(),1,1) AS '4', CONVERT(tinyint,0x08) & SUBSTRING(Context_Info(),1,1) AS '8', CONVERT(tinyint,0x10) & SUBSTRING(Context_Info(),1,1) AS '16', CONVERT(tinyint,0x20) & SUBSTRING(Context_Info(),1,1) AS '32', CONVERT(tinyint,0x40) & SUBSTRING(Context_Info(),1,1) AS '64', CONVERT(tinyint,0x80) & SUBSTRING(Context_Info(),1,1) AS '128'


You can also store strings in it.

DECLARE @MyStatus VARBINARY(128); SET @MyStatus = CAST('TEST' AS VARBINARY(128)); SET Context_Info @MyStatus; SELECT CAST(Context_Info() AS VARCHAR) -- Or substring :D SELECT CAST(SUBSTRING(CONTEXT_INFO(), 1, 4) AS VARCHAR)



This Context_Info value could be useful to store a value for the session and change the control flow of a trigger.