SQL Server 2005 includes some great new dynamic management views and functions to help find out what is going on. These three in particular work quite well together.
dm_exec_sessions can be joined to the dm_exec_requests to obtain data on who is currently executing what. This will return a sql_handle for which the function dm_exec_sql_test can be used to get actual sql text. In order to get the sql text fro every session returned we can use a new type of join CROSS APPLY. This will execute a UDF for every row.
Putting it all together, here is a stored proc "sp_whassup" that will list who is currently online, what stored proc they are executing and the sql for the stored proc. This is kinda like sp_who.
CREATE PROCEDURE [dbo].[sp_whassup]ASBEGINselect object_name(objectid,db_id()) as proc_name, st.text, login_name,r.session_id, r.request_id,e.status, r.start_time, host_name,program_namefrom sys.dm_exec_requests rinner join sys.dm_exec_sessions eon e.session_id=r.session_idcross applysys.dm_exec_sql_text(sql_handle) stEND
In my next blog I will show how to use these new views to convert a stored procedure into a "singleton", so that only one occurrence of a the stored procedure can be run at one time.