What is the scope of CONTEXT_INFO in SQL Server?

前端 未结 2 2013
误落风尘
误落风尘 2021-02-04 00:14

I am using CONTEXT_INFO to pass a username to a delete trigger for the purposes of an audit/history table. I\'m trying to understand the scope of CONTEXT_INFO and if I am creat

2条回答
  •  生来不讨喜
    2021-02-04 00:37

    Context info has no scope (in the sense of language variables scope) and is bound to the session lifetime. Once set, the context info stay at the value set until the connection is closed (the session terminates) or until a new value is set. Since execution on a session is always sequential, there is no question of concurrency.

    IF you set the context info in a procedure, any trigger subsequently executed on that session will see the newly set context info value. Setting the user id value in the context info, as you propose, and using it in triggers is the typical example of the context info use and is perfectly safe in regard to concurrency, since basically there is no concurrency to speak of. If you plan to set the context info in a stored procedure and then rely on it in a trigger that runs due to deletes that occur in the said procedure, then your batch did not finish yet so, according to the article you linked, you retrieve the conetxt info from the sys.dm_exec_requests DMV or from the CONTEXT_INFO() function. It will not yet be pushed in sys.dm_exec_sessions, that can only happen after you exit the stored procedure and finish any other call in the T-SQL batch sent to the server (the 'request').

提交回复
热议问题