The syntax you're looking for will be very similar to this:
create event session longrunning_statements on server
add event sqlserver.sql_statement_completed
(
where (duration > 5000000)
)
add target package0.asynchronous_file_target
(Set filename='c:\capture\xe_longrunning_statement.xel',
metadatafile='c:\capture\xe_longrunning_statement.xem');
alter event sesession longrunning_statements on server state=start;
This will set up an event session which will track an sql statement that takes longer than 5 seconds to complete. The duration filter is based on microseconds btw.
If you wanted to restrict this to a specific database (in this case the db with database id=5, then you could change the filter to:
where (duration > 5000000 and database_id=5)
Lots of other filters as well to tie it down to specific sessions or users if required.
This event session will log it's results out to a file (c:\capture\xe_longrunning_statement.xel
) which can be read in with the fn_xe_file_target_read_file
function like so:
SELECT *
FROM
sys.fn_xe_file_target_read_file
(
'c:\capture\xe_longrunning_statement*.xel',
'c:\capture\xe_longrunning_statement.xem',
null,
null
);
(Note that I've used 2008R2 standards for tge xel/xem files and setting up the target. It's slightly different in 2012, but this syntax would still work). The * in the filename is to let the function know you want to load up all of the files if they've rolled over due to size.
You'll then need to parse the data out through your XML tools of choice.
Once you're done with the capture, you can tidy up as follows:
alter event session longrunning_statements on server state=stop;
drop event session longrunning_statements;
One of the best online resources is Jonathan Kehayais' 31 days of Exteneded Events - https://www.sqlskills.com/blogs/jonathan/an-xevent-a-day-31-days-of-extended-events/ - which walks you through the topic with plenty of examples.
Best Answer
If you are just looking to log this information, you can set up an Extended Events session and capture the
error_reported
event. Here is an example:To test this out, here is a test error with
RAISERROR()
:Then by looking at the XE log through the sys.fn_xe_file_target_read_file system function, you will be able to see all of the logged errors.