{"id":4343,"date":"2015-12-15T00:56:26","date_gmt":"2015-12-14T19:26:26","guid":{"rendered":"http:\/\/sqlhints.com\/?p=4343"},"modified":"2015-12-31T23:23:31","modified_gmt":"2015-12-31T17:53:31","slug":"session_context-in-sql-server-2016","status":"publish","type":"post","link":"https:\/\/sqlhints.com\/2015\/12\/15\/session_context-in-sql-server-2016\/","title":{"rendered":"SESSION_CONTEXT in Sql Server 2016"},"content":{"rendered":"<p style=\"text-align: justify;\">In .Net we have Session object which provides a mechanism to store and retrieve values for a user as user navigates ASP.NET pages in a Web application for that session. With Sql Server 2016 we are getting the similar feature in Sql Server, where we can store multiple key and value pairs which are accessible throughout that session. The key and value pairs can be set by the <strong>sp_set_session_context<\/strong> system stored procedure and these set values can be retrieved one at a time by using the <strong>SESSION_CONTEXT<\/strong> built in function.<\/p>\n<p style=\"text-align: justify;\">This article explains in detail with extensive list of examples on how we can store the information that can be accessed anywhere in that session.<\/p>\n<p style=\"text-align: justify;\">In this article for the Session Context key value pairs I will be interchangeably referring them as <strong>Session Variables<\/strong>. I hope most of the .Net developers too prefer calling them as session variables.<\/p>\n<p style=\"text-align: justify;\"><strong>EXAMPLE 1<\/strong>: This example demonstrates how we can set the session context key named EmployeeId with it\u2019s value and retrieving this set keys value.<\/p>\n<pre class=\"brush: sql; gutter: false\">\r\n--Set the session variable EmployeeId value\r\nEXEC sp_set_session_context &#039;EmployeeId&#039;, 5000\r\n--Retrieve the session variable EmployeeId value\r\nSELECT SESSION_CONTEXT(N&#039;EmployeeId&#039;) AS EmployeeId\r\n<\/pre>\n<p><strong>RESULT:<\/strong><br \/>\n<a href=\"https:\/\/sqlhints.com\/wp-content\/uploads\/2015\/12\/SessionContext-Sql-Example-1-1.jpg\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/sqlhints.com\/wp-content\/uploads\/2015\/12\/SessionContext-Sql-Example-1-1.jpg\" alt=\"SessionContext Sql Example 1 1\" width=\"450\" height=\"150\" class=\"alignnone size-full wp-image-4344\" \/><\/a><\/p>\n<p style=\"text-align: justify;\">Let us try to re-get the session context key EmployeeId value, but this time while specifying the key EmployeeId parameter skipping the prefix N:<\/p>\n<pre class=\"brush: sql; gutter: false\">\r\n--Retrieve the session variable EmployeeId value\r\nSELECT SESSION_CONTEXT(&#039;EmployeeId&#039;) AS EmployeeId\r\n<\/pre>\n<p><strong>RESULT:<\/strong><\/p>\n<p style=\"text-align: justify;color: red;\">Msg 8116, Level 16, State 1, Line 2<br \/>\nArgument data type varchar is invalid for argument 1 of session_context function.<\/p>\n<p style=\"text-align: justify;\">From the result it is clear that the SESSION_CONTEXT function always expects the key parameter passed to it should of type NVarchar.<\/p>\n<p style=\"text-align: justify;\">Let us re-execute the above statement by prefixing the key parameter by N<\/p>\n<pre class=\"brush: sql; gutter: false\">\r\n--Retrieve the session variable EmployeeId value\r\nSELECT SESSION_CONTEXT(N&#039;EmployeeId&#039;) AS EmployeeId\r\n<\/pre>\n<p><strong>RESULT:<\/strong><br \/>\n<a href=\"https:\/\/sqlhints.com\/wp-content\/uploads\/2015\/12\/SessionContext-Sql-Example-1-2.jpg\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/sqlhints.com\/wp-content\/uploads\/2015\/12\/SessionContext-Sql-Example-1-2.jpg\" alt=\"SessionContext Sql Example 1 2\" width=\"450\" height=\"150\" class=\"alignnone size-full wp-image-4345\" srcset=\"https:\/\/sqlhints.com\/wp-content\/uploads\/2015\/12\/SessionContext-Sql-Example-1-2.jpg 540w, https:\/\/sqlhints.com\/wp-content\/uploads\/2015\/12\/SessionContext-Sql-Example-1-2-300x101.jpg 300w\" sizes=\"auto, (max-width: 450px) 100vw, 450px\" \/><\/a><\/p>\n<p style=\"text-align: justify;\"><strong>EXAMPLE 2:<\/strong> Below example shows how we can update the Session variable value<\/p>\n<pre class=\"brush: sql; gutter: false\">\r\n--Set session variable EmployeeName value\r\nEXEC sp_set_session_context @key = &#039;EmployeeName&#039;, \r\n  @value=&#039;Basavaraj&#039;\r\n--Retrieve the session variable EmployeeName value\r\nSELECT SESSION_CONTEXT(N&#039;EmployeeName&#039;) EmployeeName\r\n--Re-Set the EmployeeName session variable value\r\nEXEC sp_set_session_context @key =&#039;EmployeeName&#039;,\r\n  @value=&#039;Basavaraj Biradar&#039;\r\n--Retrieve the update session variable EmployeeName value\r\nSELECT SESSION_CONTEXT(N&#039;EmployeeName&#039;) EmployeeName\r\n<\/pre>\n<p><strong>RESULT:<\/strong><br \/>\n<a href=\"https:\/\/sqlhints.com\/wp-content\/uploads\/2015\/12\/updating-session-context-value-Example-2.jpg\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/sqlhints.com\/wp-content\/uploads\/2015\/12\/updating-session-context-value-Example-2.jpg\" alt=\"updating session context value Example 2\" width=\"550\" height=\"381\" class=\"alignnone size-full wp-image-4349\" \/><\/a><\/p>\n<p style=\"text-align: justify;\"><strong>EXAMPLE 3:<\/strong> Below example demonstrates a session variable can be declared as readonly<\/p>\n<p style=\"text-align: justify;\">First create the readonly session variable City by using the following statement. We can mark a session variable as readonly by specying the parameter @read_only value as 1. This parameter is optional, if we don\u2019t specify it or if we specify this parameter value as 0 then Sql Server will not allow to update this value later.<\/p>\n<pre class=\"brush: sql; gutter: false\">\r\n--create a readonly session variable City\r\nEXEC sp_set_session_context @key = &#039;City&#039;, @value=&#039;Bangalore&#039;, \r\n  @read_only = 1\r\n--Retrieve the session variable City value\r\nSELECT SESSION_CONTEXT(N&#039;City&#039;) City\r\n<\/pre>\n<p><strong>RESULT:<\/strong><br \/>\n<a href=\"https:\/\/sqlhints.com\/wp-content\/uploads\/2015\/12\/SessionContext-Setting-Readonly-Variable-value-Example-3.jpg\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/sqlhints.com\/wp-content\/uploads\/2015\/12\/SessionContext-Setting-Readonly-Variable-value-Example-3.jpg\" alt=\"SessionContext Setting Readonly Variable value Example 3\" width=\"550\" height=\"234\" class=\"alignnone size-full wp-image-4352\" \/><\/a><\/p>\n<p style=\"text-align: justify;\">Now try to update the read-only session variable City value by the following statement<\/p>\n<pre class=\"brush: sql; gutter: false\">\r\n--try to update the read-only City session variable value\r\nEXEC sp_set_session_context @key =&#039;City&#039;,@value=&#039;Bengaluru&#039;\r\n<\/pre>\n<p><strong>RESULT:<\/strong><\/p>\n<p style=\"text-align: justify;color: red;\">Msg 15664, Level 16, State 1, Procedure sp_set_session_context, Line 1<br \/>\nCannot set key &#8216;City&#8217; in the session context. The key has been set as read_only for this session.<\/p>\n<p><strong>SYNTAX of sp_set_session_context:<\/strong><\/p>\n<pre class=\"brush: sql; gutter: false\">\r\nsp_set_session_context [ @key= ] &#039;key&#039;, [ @value= ] &#039;value&#039;\r\n    [ , [ @read_only = ] { 0 | 1 } ]\r\n<\/pre>\n<p style=\"text-align: justify;\">Where: @key parameter is of type SYSNAME, @value is of type SQL_VARIANT and @read_only parameter is of type BIT<\/p>\n<p><strong>SYNTAX of SESSION_CONTEXT<\/strong><\/p>\n<pre class=\"brush: sql; gutter: false\">\r\nSESSION_CONTEXT(N&#039;key&#039;)\r\n<\/pre>\n<p style=\"text-align: justify;\">Where:&#8217;key&#8217; parameter to this function is of type SYSNAME and the return type of this function is SQL_VARIANT<\/p>\n<p style=\"text-align: justify;\"><strong>EXAMPLE 4:<\/strong> Below example demonstrates how a session variable can be accessed in stored procedure which is set somewhere outside.<\/p>\n<p style=\"text-align: justify;\">Let us create a stored procedure GetCountry by the following script:<\/p>\n<pre class=\"brush: sql; gutter: false\">\r\nCREATE PROCEDURE GetCountry\r\nAS\r\nBEGIN\r\n\tSELECT SESSION_CONTEXT(N&#039;Country&#039;) Country\r\nEND\r\n<\/pre>\n<p style=\"text-align: justify;\">Then by using the following script create the session variable Country<\/p>\n<pre class=\"brush: sql; gutter: false\">\r\n--create a readonly session variable Country\r\nEXEC sp_set_session_context @key = &#039;Country&#039;, @value=&#039;India&#039;\r\n--Retrieve the session variable Country value\r\nSELECT SESSION_CONTEXT(N&#039;Country&#039;) Country\r\n<\/pre>\n<p><strong>RESULT:<\/strong><br \/>\n<a href=\"https:\/\/sqlhints.com\/wp-content\/uploads\/2015\/12\/Session-Context-Example-4-1.jpg\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/sqlhints.com\/wp-content\/uploads\/2015\/12\/Session-Context-Example-4-1.jpg\" alt=\"Session Context Example 4 1\" width=\"550\" height=\"245\" class=\"alignnone size-full wp-image-4356\" \/><\/a><\/p>\n<p style=\"text-align: justify;\">Now in the same session execute the stored procedure GetCountry and see whether this SP has access to the Session variable Country:<\/p>\n<pre class=\"brush: sql; gutter: false\">\r\nEXEC GetCountry\r\n<\/pre>\n<p><strong>RESULT:<\/strong><br \/>\n<a href=\"https:\/\/sqlhints.com\/wp-content\/uploads\/2015\/12\/Accessing-SessionContext-from-the-Stored-Procedure-Example-4-2.jpg\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/sqlhints.com\/wp-content\/uploads\/2015\/12\/Accessing-SessionContext-from-the-Stored-Procedure-Example-4-2.jpg\" alt=\"Accessing SessionContext from the Stored Procedure Example 4 2\" width=\"250\" height=\"155\" class=\"alignnone size-full wp-image-4357\" \/><\/a><\/p>\n<p style=\"text-align: justify;\"><strong>EXAMPLE 5:<\/strong> Below example demonstrates the behavior when we try to fetch a non-existent session variable<\/p>\n<pre class=\"brush: sql; gutter: false\">\r\nSELECT SESSION_CONTEXT(N&#039;Continent&#039;) Continent\r\n<\/pre>\n<p><strong>RESULT:<\/strong><br \/>\n<a href=\"https:\/\/sqlhints.com\/wp-content\/uploads\/2015\/12\/Non-Existent-SessionContext-Sql-Example-5.jpg\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/sqlhints.com\/wp-content\/uploads\/2015\/12\/Non-Existent-SessionContext-Sql-Example-5.jpg\" alt=\"Non Existent SessionContext Sql Example 5\" width=\"350\" height=\"159\" class=\"alignnone size-full wp-image-4358\" \/><\/a><\/p>\n<p style=\"text-align: justify;\">From the result it is clear that, NULL value will be returned by SESSION_CONTEXT function if we try to fetch non-existent session variable.<\/p>\n<p style=\"text-align: justify;\">The maximum size of the session context is limited to 256 kb. So there is no specific limit or the number of key and value pairs that can be stored in the Session Context as long as the total size is less than 256 Kb and it raises an error if the total size cross this max size limit. Note this limit of 256 Kb is at session level, so we can have multiple sessions at the same time with each session max limit is 256 kb.<\/p>\n<p style=\"text-align: justify;\">We can check the overall memory usage for the session context across all the session by using the below statement:<\/p>\n<pre class=\"brush: sql; gutter: false\">\r\nSELECT cache_address, name, pages_kb, pages_in_use_kb, \r\n\tentries_count, entries_in_use_count\r\nFROM sys.dm_os_memory_cache_counters \r\nWHERE TYPE = &#039;CACHESTORE_SESSION_CONTEXT&#039;\r\n<\/pre>\n<p><strong>RESULT:<\/strong><br \/>\n<a href=\"https:\/\/sqlhints.com\/wp-content\/uploads\/2015\/12\/SessionContext-Memory-Usage-Details-in-Sql-Example-6.jpg\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/sqlhints.com\/wp-content\/uploads\/2015\/12\/SessionContext-Memory-Usage-Details-in-Sql-Example-6.jpg\" alt=\"SessionContext Memory Usage Details in Sql Example 6\" width=\"580\" height=\"269\" class=\"alignnone size-full wp-image-4361\" \/><\/a><\/p>\n<p style=\"text-align: justify;\">From the above result we can see that we have two active sql sessions with session context info stored. Out of these two session, the 2nd session is having 200 key value pairs stored in it and it is using 88 kb. And below is the script which is used to generate the 200 key value pairs:<\/p>\n<pre class=\"brush: sql; gutter: false\">\r\nDECLARE @Counter INT = 0,  @KeyName SYSNAME\r\nWHILE @Counter &lt; 200\r\nBEGIN\r\n  SET @KeyName = N&#039;Key&#039; + CAST(@Counter AS NVARCHAR);\r\n  EXEC sys.sp_set_session_context @key = @KeyName, @value = 20\r\n  SET @Counter += 1;\r\nEND\r\n<\/pre>\n<p><strong>[ALSO READ]<\/strong><\/p>\n<ul>\n<li><a href=\"https:\/\/sqlhints.com\/2015\/10\/25\/json-in-sql-server-2016\/\" target=\"_blank\">Native JSON Support in Sql Server 2016<\/a>\n<ul>\n<li><a href=\"https:\/\/sqlhints.com\/2015\/11\/15\/for-json-clause-in-sql-server-2016\/\" target=\"_blank\">FOR JSON Clause in Sql Server 2016<\/a><\/li>\n<li><a href=\"https:\/\/sqlhints.com\/2015\/11\/22\/openjson-function-in-sql-server-2016\/\" target=\"_blank\">OPENJSON Function in Sql Server 2016<\/a><\/li>\n<li><a href=\"https:\/\/sqlhints.com\/2015\/11\/15\/isjson-function-in-sql-server-2016\/\" target=\"_blank\">ISJSON Function in Sql Server 2016<\/a><\/li>\n<li><a href=\"https:\/\/sqlhints.com\/2015\/11\/15\/json_value-function-in-sql-server-2016\/\" target=\"_blank\">JSON_VALUE Function in Sql Server 2016<\/a><\/li>\n<li><a href=\"https:\/\/sqlhints.com\/2015\/11\/15\/json_query-function-in-sql-server-2016\/\" target=\"_blank\">JSON_QUERY Function in Sql Server 2016<\/a><\/li>\n<li><a href=\"https:\/\/sqlhints.com\/2015\/11\/15\/lax-and-strict-json-path-modes-in-sql-server-2016\/\" target=\"_blank\">lax and strict JSON Path modes in Sql Server 2016<\/a><\/li>\n<li><a href=\"https:\/\/sqlhints.com\/2015\/11\/28\/indexing-strategy-for-json-value-in-sql-server-2016\/\" target=\"_blank\">Indexing Strategy for JSON Value in Sql Server 2016<\/a><\/li>\n<\/ul>\n<\/li>\n<li><a href=\"https:\/\/sqlhints.com\/2015\/11\/12\/drop-if-exists-statement-in-sql-server-2016\/\" target=\"_blank\">DROP IF EXISTS Statement in Sql Server 2016<\/a><\/li>\n<li><a href=\"https:\/\/sqlhints.com\/2015\/11\/29\/compare-execution-plan-in-sql-server-2016\/\" target=\"_blank\">Compare Execution Plans in Sql Server 2016<\/a><\/li>\n<li><a href=\"https:\/\/sqlhints.com\/2015\/12\/11\/live-query-statistics-in-sql-server-2016\/\" target=\"_blank\">Live Query Statistics in Sql Server 2016<\/a><\/li>\n<li><a href=\"https:\/\/sqlhints.com\/2015\/12\/12\/datediff_big-function-in-sql-server-2016\/\" target=\"_blank\">DATEDIFF_BIG Function in Sql Server 2016<\/a><\/li>\n<li><a href=\"https:\/\/sqlhints.com\/2015\/12\/12\/difference-between-datediff-and-datediff_big-functions-in-sql-server\/\" target=\"_blank\">Difference between DATEDIFF and DATEDIFF_BIG functions in Sql Server<\/a><\/li>\n<li><a href=\"https:\/\/sqlhints.com\/2015\/12\/15\/session_context-in-sql-server-2016\/\" target=\"_blank\">SESSION_CONTEXT in Sql Server 2016<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>In .Net we have Session object which provides a mechanism to store and retrieve values for a user as user navigates ASP.NET pages in a Web application for that session. With Sql Server 2016 we are getting the similar feature in Sql Server, where we can store multiple key and value pairs which are accessible &hellip; <a href=\"https:\/\/sqlhints.com\/2015\/12\/15\/session_context-in-sql-server-2016\/\" class=\"more-link\">Continue reading <span class=\"screen-reader-text\">SESSION_CONTEXT in Sql Server 2016<\/span> <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2}},"categories":[3,830],"tags":[975,980,979,974,970,981,982,978,977,971,972,968,969,964,966,967,965,973,963,976],"class_list":["post-4343","post","type-post","status-publish","format-standard","hentry","category-sql-server","category-sql-server-2016","tag-argument-data-type-varchar-is-invalid-for-argument-1-of-session_context-function","tag-cannot-set-key-city-in-the-session-context-the-key-has-been-set-as-read_only-for-this-session","tag-msg-15664-level-16-state-1-procedure-sp_set_session_context-line-1","tag-msg-8116-level-16-state-1-line-2","tag-session-context-key-value-pairs-sql","tag-session-context-maximum-size-limit-is-256-kb","tag-session-context-memory-usage-details-by-the-dmv-sys-dm_os_memory_cache_counters","tag-session-context-readonly","tag-session-context-readonly-key","tag-session-context-sql-2016","tag-session-context-sql-server-2016","tag-session-in-sql-server","tag-session-variables-in-sql","tag-session_context","tag-session_context-in-sql-2016","tag-session_context-in-sql-server-2016","tag-session_context-sql","tag-sp_set_session_context","tag-sql-session_context","tag-updating-session-context-in-sql-server"],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p3xNAz-183","_links":{"self":[{"href":"https:\/\/sqlhints.com\/wp-json\/wp\/v2\/posts\/4343","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sqlhints.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sqlhints.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sqlhints.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/sqlhints.com\/wp-json\/wp\/v2\/comments?post=4343"}],"version-history":[{"count":17,"href":"https:\/\/sqlhints.com\/wp-json\/wp\/v2\/posts\/4343\/revisions"}],"predecessor-version":[{"id":4526,"href":"https:\/\/sqlhints.com\/wp-json\/wp\/v2\/posts\/4343\/revisions\/4526"}],"wp:attachment":[{"href":"https:\/\/sqlhints.com\/wp-json\/wp\/v2\/media?parent=4343"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sqlhints.com\/wp-json\/wp\/v2\/categories?post=4343"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sqlhints.com\/wp-json\/wp\/v2\/tags?post=4343"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}