Permission error when using sys.dm_exec_input_buffer with @@SPID When I run this blob of SQL on SQL Server 2016 or an Azure SQL DB:

--hello world
SELECT      event_info
FROM        sys.dm_exec_requests req
CROSS APPLY sys.dm_exec_input_buffer(req.session_id, req.request_id)
WHERE       req.session_id = @@SPID


I get this error, followed by the expected results:

Msg 300, Level 14, State 1, Line 5
VIEW SERVER STATE permission was denied on object 'server', database 'master'.
Msg 297, Level 16, State 1, Line 5
The user does not have permission to perform this action.
--hello world
SELECT      event_info
FROM        sys.dm_exec_requests req
CROSS APPLY sys.dm_exec_input_buffer(req.session_id, req.request_id)
WHERE       req.session_id = @@SPID


The documentation for sys.dm_exec_input_buffer states (emphasis mine):


  On SQL Server, if the user has VIEW SERVER STATE permission, the user will see all executing sessions on the instance of SQL Server; otherwise, the user will see only the current session.


Thus, according to the documentation, I am allowed to access this data. Why, then, is the error being raised?
Using the condition WHERE req.session_id = &lt;some value&gt; triggers the error condition. Then the line is ignored, and the rest runs correctly. Try executing:

SELECT      event_info
FROM        sys.dm_exec_requests req
CROSS APPLY sys.dm_exec_input_buffer(req.session_id, req.request_id)


without the WHERE clause, and you should get the correct output.

tl;dr Looking for a specific session_id triggers the error.