title: SQL Server query to show last activity time for current session
body: <p>Back end: SQL Server 2017 Express</p>
  <p>Front End: Microsoft Access 2019 with ODBC linked tables to the SQL Server database</p>
  <p>Objective: To detect inactivity of say 30 minutes in the current session, and then exit from Access</p>
  <p>I would like a SQL Server query (to be called from the front-end Access database, via a timer) which will return the date/time of the last SQL statement (e.g. select/insert/update/delete) for the current session, so that the Access application can exit after a defined period of inactivity.</p>
  <p>So far, I have looked at sp_who, sp_who2, sysprocesses, dm_exec_connections, dm_db_index_usage_stats and dm_exec_sessions.</p>
  <p>Whilst these return useful looking columns such as LastBatch, the problem is that the act of querying the database updates the return value. For instance, if I run sp_who2 and look at the row for my SPID, the value of LastBatch is always the same as GetDate().</p>
  <p>I know that the options above would work if I was monitoring another session (SPID) but I'm looking for a way to find the time of last activity (excluding sp_who2 etc) <strong>for my own session</strong>.</p>
  <p>Any suggestions?</p>