SQL Server Tutorial Advanced

Advanced Use of SQL Server Extended Events for Monitoring


Introduction

SQL Server Extended Events is a powerful tool for monitoring and troubleshooting database performance. This guide explores advanced techniques for using Extended Events with sample code and examples.

1. Creating an Extended Events Session

To monitor specific events, you need to create an Extended Events session. Define events, actions, and predicates for the session.

        -- Create an Extended Events session
        CREATE EVENT SESSION MySession
        ON SERVER
        ADD EVENT sqlserver.sql_statement_completed,
        ADD EVENT sqlserver.sql_batch_completed
        ADD TARGET package0.asynchronous_file_target
        (SET FILENAME = N'C:XELogsMySession.xel');
    

2. Configuring Event Predicates

You can filter events by adding predicates to your session to capture specific conditions or criteria.

        -- Add a predicate to capture specific queries
        ALTER EVENT SESSION MySession
        ON SERVER
        ADD EVENT sqlserver.sql_statement_completed
        (WHERE ([sqlserver].[sql_text] like '%SELECT%'));
    

3. Starting and Stopping Sessions

Once your session is configured, you can start and stop it to capture events during specific timeframes.

        -- Start the Extended Events session
        ALTER EVENT SESSION MySession ON SERVER STATE = START;
        -- Stop the Extended Events session
        ALTER EVENT SESSION MySession ON SERVER STATE = STOP;
    

4. Analyzing Captured Events

To analyze captured events, you can query the Extended Events data using SQL queries. This helps you gain insights into performance and issues.

        -- Query Extended Events data
        SELECT
            name AS EventName,
            object_name AS ObjectName,
            event_data.value('(event/action[@name=`sql_text`]/value)[1]', 'nvarchar(max)') AS SQLStatement
        FROM sys.fn_xe_file_target_read_file('C:XELogsMySession*.xel', null, null, null);
    

5. Advanced Scenarios

SQL Server Extended Events can be used for advanced scenarios, including tracking query execution, monitoring deadlocks, and capturing specific error conditions.

        -- Capture deadlock events
        CREATE EVENT SESSION DeadlockSession
        ON SERVER
        ADD EVENT sqlserver.xml_deadlock_report
        ADD TARGET package0.event_file
        (SET FILENAME = N'C:XELogsDeadlockSession.xel');
    

Conclusion

Advanced use of SQL Server Extended Events offers valuable insights into database performance and troubleshooting. By creating sessions, configuring event predicates, starting and stopping sessions, and analyzing captured data, you can effectively monitor and troubleshoot your SQL Server environment.

Written by Surfside Media

Senior Full Stack Developer specializing in Web Technologies.