Obiekty docelowe dla zdarzeń rozszerzonych w programie SQL Server

Dotyczy: SQL Server Azure SQL Managed Instance

W tym artykule wyjaśniono, kiedy i jak używać obiektów docelowych package0 dla zdarzeń rozszerzonych w programie SQL Server. Dla każdego celu niniejszy artykuł wyjaśnia:

  • Jego zdolności w zakresie gromadzenia i raportowania danych wysyłanych przez zdarzenia.
  • Jego parametry, z wyjątkiem przypadków, gdy parametr nie wymaga wyjaśnień.

Przykład XQuery

Sekcja ring_buffer zawiera przykład użycia języka XQuery w języku Transact-SQL w celu skopiowania ciągu kodu XML do relacyjnego zestawu wierszy.

Warunki wstępne

  • Zapoznaj się z podstawami zdarzeń rozszerzonych, zgodnie z opisem w temacie Szybki start: zdarzenia rozszerzone w programie SQL Server.

  • Zainstalowano najnowszą wersję często aktualizowanego narzędzia SQL Server Management Studio (SSMS). Aby uzyskać szczegółowe informacje, zobacz:

  • W programie SSMS.exe dowiedz się, jak za pomocą Eksploratora obiektów kliknąć prawym przyciskiem myszy węzeł docelowy w sesji zdarzenia, aby ułatwić wyświetlanie danych wyjściowych.

    • Dane zdarzenia są przechwytywane jako ciąg znaków XML. Jednak w tym artykule dane są wyświetlane w wierszach relacyjnych. Program SSMS został użyty do wyświetlenia danych, a następnie skopiowany i wklejony do tego artykułu.
    • Alternatywna technika T-SQL do generowania zestawów wierszy z XML została wyjaśniona w sekcji ring_buffer. Obejmuje XQuery.

Parametry, akcje i pola

W języku Transact-SQL instrukcja CREATE EVENT SESSION ma kluczowe znaczenie dla zdarzeń rozszerzonych. Aby napisać oświadczenie, często potrzebujesz listy i opisu:

  • Pola powiązane z wybranym wydarzeniem.
  • Parametry powiązane z wybranym celem.

Instrukcje SELECT, które zwracają takie listy z widoków systemowych, są dostępne do skopiowania z następującego artykułu w sekcji C:

Parametry, pola i akcje używane w kontekście rzeczywistej instrukcji CREATE EVENT SESSION można zobaczyć pod tym linkiem.

etw_classic_sync_target cel

Zdarzenia programu SQL Server Extended mogą współpracować ze śledzeniem zdarzeń systemu Windows (ETW) w celu monitorowania aktywności systemu. Aby uzyskać więcej informacji, zobacz:

Ten obiekt docelowy ETW przetwarza synchronicznie dane, które otrzymuje, podczas gdy większość obiektów docelowych przetwarza asynchronicznie.

event_counter cel

Obiekt docelowy event_counter zlicza jedynie, ile razy wystąpi każde określone zdarzenie.

W przeciwieństwie do większości innych celów:

  • event_counter nie ma żadnych parametrów.
  • W przeciwieństwie do większości obiektów docelowych, event_counter obiekt docelowy przetwarza synchronicznie otrzymane dane.
    • Synchroniczny jest akceptowalny dla prostych event_counter, ponieważ event_counter wymaga tak mało przetwarzania.
    • Aparat bazy danych odłączy się od każdego obiektu docelowego, który jest zbyt wolny, co grozi spowolnieniem wydajności aparatu bazy danych. Jest to jeden z powodów, dla których większość celów przetwarza się asynchronicznie.

Przykładowe dane wyjściowe przechwycone przez event_counter

package_name   event_name         count
------------   ----------         -----
sqlserver      checkpoint_begin   4

Dalej jest SESJA TWORZENIA ZDARZENIA, która doprowadziła do poprzednich wyników. W tym teście, na WYDARZENIU... WHERE, pole package0.counter zostało użyte do przerwania liczenia po wzroście liczenia do 4.

.SQL
CREATE EVENT SESSION [event_counter_1]
    ON SERVER 
    ADD EVENT sqlserver.checkpoint_begin   -- Test by issuing CHECKPOINT; statements.
    (
        WHERE ([package0].[counter] <= (4))   -- A predicate filter.
    )
    ADD TARGET package0.event_counter
    WITH
    (
        MAX_MEMORY = 4096 KB,
        MAX_DISPATCH_LATENCY = 3 SECONDS
    );

event_file cel

Obiekt docelowy event_file zapisuje dane wyjściowe sesji zdarzenia z bufora do pliku na dysku:

  • Parametr filename= określa się w klauzuli ADD TARGET.
    • .xel musi być rozszerzeniem pliku.
  • Wybrana nazwa pliku jest używana przez system jako prefiks, do którego dołączana jest długa liczba całkowita oparta na dacie i godzinie, po której następuje rozszerzenie xel.

UTWÓRZ SESJĘ ZDARZENIA z event_file obiektem docelowym

Dalej jest CREATE EVENT SESSION, z którą testowaliśmy. Jedna z klauzul ADD TARGET określa event_file.

.SQL
CREATE EVENT SESSION [locks_acq_rel_eventfile_22]
    ON SERVER 
    ADD EVENT sqlserver.lock_acquired
    (
        SET
            collect_database_name=(1),
            collect_resource_description=(1)

        ACTION (sqlserver.sql_text,sqlserver.transaction_id)

        WHERE
        (
            [database_name]=N'InMemTest2'
            AND
            [object_id]=(370100359)
        )
    ),
    ADD EVENT sqlserver.lock_released
    (
        SET
            collect_database_name=(1),
            collect_resource_description=(1)

        ACTION(sqlserver.sql_text,sqlserver.transaction_id)

        WHERE
        (
            [database_name]=N'InMemTest2'
            AND
            [object_id]=(370100359)
        )
    )
    ADD TARGET package0.event_counter,
    ADD TARGET package0.event_file
    (
        SET     filename=N'C:\Junk\locks_acq_rel_eventfile_22-.xel'
    )
    WITH
    (
        MAX_MEMORY=4096 KB,
        MAX_DISPATCH_LATENCY=10 SECONDS
    );

sys.fn_xe_file_target_read_file funkcja;

Obiekt docelowy event_file przechowuje otrzymane dane w formacie binarnym, który nie jest czytelny dla człowieka. Język Transact-SQL może raportować zawartość pliku xel przez polecenie SELECTing z funkcji sys.fn_xe_file_target_read_file.

W przypadku programu SQL Server 2016 i nowszych wersji następujące T-SQL SELECT zgłosiło dane. Sufiks *.xel w nazwie pliku jest wymagany.

.SQL
SELECT f.*
        --,CAST(f.event_data AS XML)  AS [Event-Data-Cast-To-XML]  -- Optional
    FROM
        sys.fn_xe_file_target_read_file(
            'C:\junk\locks_acq_rel_eventfile_22-*.xel',
            null, null, null)  AS f;

W przypadku programu SQL Server 2014 SELECT podobny do poniższego raportuje dane. Po programie SQL Server 2014 pliki xem nie są już używane.

.SQL
SELECT f.*
        --,CAST(f.event_data AS XML)  AS [Event-Data-Cast-To-XML]  -- Optional
    FROM
        sys.fn_xe_file_target_read_file(
            'C:\junk\locks_acq_rel_eventfile_22-*.xel',
            'C:\junk\metafile.xem',
            null, null)  AS f;

Oczywiście można również ręcznie użyć interfejsu użytkownika programu SSMS, aby wyświetlić dane xel.

Dane przechowywane w event_file celu

Dalej jest raport z SELECTing from , w SQL Server 2016.sys.fn_xe_file_target_read_file

Ouptut
module_guid                            package_guid                           object_name     event_data                                                                                                                                                                                                                                                                                          file_name                                                      file_offset
-----------                            ------------                           -----------     ----------                                                                                                                                                                                                                                                                                          ---------                                                      -----------
D5149520-6282-11DE-8A39-0800200C9A66   03FDA7D0-91BA-45F8-9875-8B6DD0B8E9F2   lock_acquired   <event name="lock_acquired" package="sqlserver" timestamp="2016-08-07T20:13:35.827Z"><action name="transaction_id" package="sqlserver"><value>39194</value></action><action name="sql_text" package="sqlserver"><value><![CDATA[  select top 1 * from dbo.T_Target;  ]]></value></action></event>   C:\junk\locks_acq_rel_eventfile_22-_0_131150744126230000.xel   11776
D5149520-6282-11DE-8A39-0800200C9A66   03FDA7D0-91BA-45F8-9875-8B6DD0B8E9F2   lock_released   <event name="lock_released" package="sqlserver" timestamp="2016-08-07T20:13:35.832Z"><action name="transaction_id" package="sqlserver"><value>39194</value></action><action name="sql_text" package="sqlserver"><value><![CDATA[  select top 1 * from dbo.T_Target;  ]]></value></action></event>   C:\junk\locks_acq_rel_eventfile_22-_0_131150744126230000.xel   11776

Docelowy histogram

Cel histogramu jest bardziej wyszukany niż cel event_counter. Histogram może wykonywać następujące czynności:

  • Policz wystąpienia dla kilku elementów osobno.
  • Zliczanie wystąpień różnych typów elementów:
    • Pola zdarzeń.
    • Akcje.

Parametr source_type jest kluczem do kontrolowania docelowego histogramu:

  • source_type=0 - Oznacza zbieranie danych dla pól zdarzeń).
  • source_type=1 - Oznacza zbieranie danych dla akcji.
    • Wartość domyślna to 1.

Domyślny parametr "slots" to 256. Jeśli przypiszesz inną wartość, wartość zostanie zaokrąglona w górę do następnej potęgi 2.

  • Na przykład slots=59 zostanie zaokrąglone w górę do =64.

Podczas sesji zdarzeń rozszerzonych z histogramem jako celem czasami można zobaczyć nieoczekiwane wyniki. Niektóre zdarzenia mogą nie być wyświetlane w tym samym czasie, gdy liczba innych zdarzeń ma wyższą wartość niż powinna.

Jest to efekt uboczny projektu docelowego histogramu. Jednostka histogramu używa funkcji mieszania do agregowania jednostek w segmentach. W związku z tym, w zależności od wyboru pola agregacji, dwa obiekty mogą być przechowywane w tym samym zasobniku i oba obiekty są wyświetlane pod nazwą tego wykonanego jako pierwszy.

Może się to również zdarzyć, gdy używasz parametru. Rozważmy następujący scenariusz:NO_EVENT_LOSS

  • Skonfigurowano sesję zdarzeń rozszerzonych, używając histogramu jako elementu docelowego i grupując według , aby zebrać wykonanie procedury przechowywanej.object_id
  • Procedura składowana jest wykonywana A. Następnie należy wykonać procedurę składowaną B.

Jeśli obie procedury składowane zwrócą tę samą wartość dla funkcji skrótu, histogram pokaże dwukrotne wykonanie procedury składowanej A, a procedura składowana B nie zostanie wyświetlona.object_id

Przykład działania dla histogramu

Na swoim TARGET... Klauzula SET, poniższa instrukcja Transact-SQL CREATE EVENT SESSION określa przypisanie parametru docelowego source_type=1. 1 oznacza, że cel histogramu śledzi akcję.

W tym przykładzie ZDARZENIE... Oferta klauzuli ACTION oferuje tylko jedno działanie do wyboru przez cel, a mianowicie . Na TARGET... SET, widzimy przypisanie przypisania.sqlos.system_thread_idsource=N'sqlos.system_thread_id'

Uwaga

Nie można dodać więcej niż jednego obiektu docelowego tego samego typu (w tym celu histogramu) na sesję zdarzenia. Nie jest również możliwe posiadanie więcej niż jednego źródła (pola akcji/zdarzenia) na cel histogramu. W związku z tym nowa sesja zdarzenia jest wymagana do śledzenia wszelkich dodatkowych pól akcji (lub zdarzenia) w nowym celu histogramu.

.SQL
CREATE EVENT SESSION [histogram_lockacquired]
    ON SERVER 
    ADD EVENT sqlserver.lock_acquired
        (
        ACTION
            (
            sqlos.system_thread_id
            )
        )
    ADD TARGET package0.histogram
        (
        SET
            filtering_event_name=N'sqlserver.lock_acquired',
            slots=(16),
            source=N'sqlos.system_thread_id',
            source_type=1
        )
    WITH
        (
        <.... (For brevity, numerous parameter assignments generated by SSMS.exe are not shown here.) ....>
        );

The following data was captured. The values under the value column were system_thread_id values. For instance, a total of 236 locks were taken under thread 6540.

value   count
-----   -----
 6540     236
 9308      91
 9668      74
10144      49
 5244      44
 2396      28

SELECT to discover available actions

The C.3 SELECT statement can find the actions that the system has available for you to specify on your CREATE EVENT SESSION statement. In the WHERE clause, you would first edit the filter to match the actions that interest you.o.name LIKE

Next is a sample rowset returned by the C.3 SELECT. The action is seen in the second row.system_thread_id

Package-Name   Action-Name                 Action-Description
------------   -----------                 ------------------
package0       collect_current_thread_id   Collect the current Windows thread ID
sqlos          system_thread_id            Collect current system thread ID
sqlserver      create_dump_all_threads     Create mini dump including all threads
sqlserver      create_dump_single_thread   Create mini dump for the current thread

Event field example for histogram

The following example sets source_type=0. The value assigned to source= is an event field (not an action).

SQL
CREATE EVENT SESSION [histogram_checkpoint_dbid]
    ON SERVER 
    ADD EVENT  sqlserver.checkpoint_begin
    ADD TARGET package0.histogram
    (
    SET
        filtering_event_name = N'sqlserver.checkpoint_begin',
        source               = N'database_id',
        source_type          = (0)
    )
    WITH
    ( <....> );

The following data was captured by the histogram target. The data shows that the database that is ID=5 experienced 7 checkpoint_begin events.

value   count
-----   -----
5       7
7       4
6       3

SELECT to discover available fields on your chosen event

The C.4 SELECT statement shows event fields that you can choose from. You would first edit the filter to be your chosen event name.o.name LIKE

The following rowset was returned by the C.4 SELECT. The rowset shows that is the only field on the event that can supply values for the histogram target.database_idcheckpoint_begin

Package-Name   Event-Name         Field-Name   Field-Description
------------   ----------         ----------   -----------------
sqlserver      checkpoint_begin   database_id  NULL
sqlserver      checkpoint_end     database_id  NULL

pair_matching target

The pair_matching target enables you to detect start events that occur without a corresponding end event. For instance, it might be a problem when a event occurs but no matching event follows in a timely manner.lock_acquiredlock_released

The system doesn't automatically match start and end events. Instead, you explain the matching to the system in your CREATE EVENT SESSION statement. When a start and end event are matched, the pair is discarded so everyone can focus on the unmatched start events.

Finding matchable fields for the start and end event pair

By using the C.4 SELECT, we see in the following rowset there are about 16 fields for the event. The rowset displayed here has been manually split to show which fields our example matched on. Some fields would be silly to try matching, such as on the of both events.lock_acquiredduration

Package-Name   Event-Name   Field-Name               Field-Description
------------   ----------   ----------               -----------------
sqlserver   lock_acquired   database_name            NULL
sqlserver   lock_acquired   mode                     NULL
sqlserver   lock_acquired   resource_0               The ID of the locked object, when lock_resource_type is OBJECT.
sqlserver   lock_acquired   resource_1               NULL
sqlserver   lock_acquired   resource_2               The ID of the lock partition, when lock_resource_type is OBJECT, and resource_1 is 0.
sqlserver   lock_acquired   transaction_id           NULL

sqlserver   lock_acquired   associated_object_id     The ID of the object that requested the lock that was acquired.
sqlserver   lock_acquired   database_id              NULL
sqlserver   lock_acquired   duration                 The time (in microseconds) between when the lock was requested and when it was canceled.
sqlserver   lock_acquired   lockspace_nest_id        NULL
sqlserver   lock_acquired   lockspace_sub_id         NULL
sqlserver   lock_acquired   lockspace_workspace_id   NULL
sqlserver   lock_acquired   object_id                The ID of the locked object, when lock_resource_type is OBJECT. For other lock resource types it will be 0
sqlserver   lock_acquired   owner_type               NULL
sqlserver   lock_acquired   resource_description     The description of the lock resource. The description depends on the type of lock. This is the same value as the resource_description column in the sys.dm_tran_locks view.
sqlserver   lock_acquired   resource_type            NULL

Example of pair_matching

The following CREATE EVENT SESSION statement specifies two events, and two targets. The pair_matching target specifies two sets of fields to match the events into pairs. The sequence of comma-delimited fields assigned to and must be the same. No tabs or newlines are allowed between the fields mentioned in the comma-delimited value, although spaces are okay.begin_matching_columns=end_matching_columns=

To narrow the results, we first selected from to find the of our test table. We added a filter for that one ID to the EVENT...WHERE clause.sys.objectsobject_id

SQL
CREATE EVENT SESSION [pair_matching_lock_a_r_33]
    ON SERVER 
    ADD EVENT sqlserver.lock_acquired
    (
        SET
            collect_database_name = (1),
            collect_resource_description = (1)

        ACTION (sqlserver.transaction_id)

        WHERE
        (
            [database_name] = 'InMemTest2'
            AND
            [object_id] = 370100359
        )
    ),
    ADD EVENT sqlserver.lock_released
    (
        SET
            collect_database_name = (1),
            collect_resource_description = (1)

        ACTION (sqlserver.transaction_id)

        WHERE
        (
            [database_name] = 'InMemTest2'
            AND
            [object_id] = 370100359
        )
    )
    ADD TARGET package0.event_counter,
    ADD TARGET package0.pair_matching
    (
        SET
            begin_event = N'sqlserver.lock_acquired',
            begin_matching_columns =
                N'resource_0, resource_1, resource_2, transaction_id, database_id',

            end_event = N'sqlserver.lock_released',
            end_matching_columns =
                N'resource_0, resource_1, resource_2, transaction_id, database_id',

            respond_to_memory_pressure = (1)
    )
    WITH
    (
        MAX_MEMORY = 8192 KB,
        MAX_DISPATCH_LATENCY = 15 SECONDS
    );

To test the event session, we purposely prevented to acquired locks from being released. We did this with the following T-SQL steps:

  1. BEGIN TRANSACTION.
  2. UPDATE MyTable....
  3. Purposely not issue a COMMIT TRANSACTION, until after we examined the targets.
  4. Later after testing, we issued a COMMIT TRANSACTION.

The simple event_counter target provided the following output rows. Because 52-50=2, the output implies we will see 2 unpaired lock_acquired events when we examine the output from the pair-matching target.

package_name   event_name      count
------------   ----------      -----
sqlserver      lock_acquired   52
sqlserver      lock_released   50

The pair_matching target provided the following output. As suggested by the event_counter output, we do indeed see two lock_acquired rows. The fact that we see these rows at all means these two lock_acquired events are unpaired.

package_name   event_name      timestamp                     database_name   duration   mode   object_id   owner_type   resource_0   resource_1   resource_2   resource_description   resource_type   transaction_id
------------   ----------      ---------                     -------------   --------   ----   ---------   ----------   ----------   ----------   ----------   --------------------   -------------   --------------
sqlserver      lock_acquired   2016-08-05 12:45:47.9980000   InMemTest2      0          S      370100359   Transaction  370100359    3            0            [INDEX_OPERATION]      OBJECT          34126
sqlserver      lock_acquired   2016-08-05 12:45:47.9980000   InMemTest2      0          IX     370100359   Transaction  370100359    0            0                                   OBJECT          34126

The rows for the unpaired lock_acquired events could include the T-SQL text, or , that took the locks. But we didn't want to bloat the display.sqlserver.sql_text

ring_buffer target

The ring_buffer target is handy for quick and simple event testing. When you stop the event session, the stored output is discarded.

In this ring_buffer section, we also show how you can use the Transact-SQL implementation of XQuery to copy the XML contents of the ring_buffer into a more readable relational rowset.

CREATE EVENT SESSION with ring_buffer

There is nothing special about this CREATE EVENT SESSION statement, which uses the ring_buffer target.

SQL
CREATE EVENT SESSION [ring_buffer_lock_acquired_4]
    ON SERVER 
    ADD EVENT sqlserver.lock_acquired
    (
        SET collect_resource_description=(1)

        ACTION(sqlserver.database_name)

        WHERE
        (
            [object_id]=(370100359)  -- ID of MyTable
            AND
            sqlserver.database_name='InMemTest2'
        )
    )
    ADD TARGET package0.ring_buffer
    (
        SET max_events_limit=(98)
    )
    WITH
    (
        MAX_MEMORY=4096 KB,
        MAX_DISPATCH_LATENCY=3 SECONDS
    );

XML output received for lock_acquired by ring_buffer

When retrieved by a SELECT statement, the content is in the form of a string of XML. The XML string that was stored by the ring_buffer target in our testing, is shown next. However, for brevity of the following XML display, all but two elements have been erased. Further, within each , a handful of extraneous elements have been deleted.<event><event><data>

XML
<RingBufferTarget truncated="0" processingTime="0" totalEventsProcessed="6" eventCount="6" droppedCount="0" memoryUsed="1032">
  <event name="lock_acquired" package="sqlserver" timestamp="2016-08-05T23:59:53.987Z">
    <data name="mode">
      <type name="lock_mode" package="sqlserver"></type>
      <value>1</value>
      <text><![CDATA[SCH_S]]></text>
    </data>
    <data name="transaction_id">
      <type name="int64" package="package0"></type>
      <value>111030</value>
    </data>
    <data name="database_id">
      <type name="uint32" package="package0"></type>
      <value>5</value>
    </data>
    <data name="resource_0">
      <type name="uint32" package="package0"></type>
      <value>370100359</value>
    </data>
    <data name="resource_1">
      <type name="uint32" package="package0"></type>
      <value>0</value>
    </data>
    <data name="resource_2">
      <type name="uint32" package="package0"></type>
      <value>0</value>
    </data>
    <data name="database_name">
      <type name="unicode_string" package="package0"></type>
      <value><![CDATA[]]></value>
    </data>
    <action name="database_name" package="sqlserver">
      <type name="unicode_string" package="package0"></type>
      <value><![CDATA[InMemTest2]]></value>
    </action>
  </event>
  <event name="lock_acquired" package="sqlserver" timestamp="2016-08-05T23:59:56.012Z">
    <data name="mode">
      <type name="lock_mode" package="sqlserver"></type>
      <value>1</value>
      <text><![CDATA[SCH_S]]></text>
    </data>
    <data name="transaction_id">
      <type name="int64" package="package0"></type>
      <value>111039</value>
    </data>
    <data name="database_id">
      <type name="uint32" package="package0"></type>
      <value>5</value>
    </data>
    <data name="resource_0">
      <type name="uint32" package="package0"></type>
      <value>370100359</value>
    </data>
    <data name="resource_1">
      <type name="uint32" package="package0"></type>
      <value>0</value>
    </data>
    <data name="resource_2">
      <type name="uint32" package="package0"></type>
      <value>0</value>
    </data>
    <data name="database_name">
      <type name="unicode_string" package="package0"></type>
      <value><![CDATA[]]></value>
    </data>
    <action name="database_name" package="sqlserver">
      <type name="unicode_string" package="package0"></type>
      <value><![CDATA[InMemTest2]]></value>
    </action>
  </event>
</RingBufferTarget>

To see the preceding XML, you can issue the following SELECT while the event session is active. The active XML data is retrieved from the system view .sys.dm_xe_session_targets

SQL
SELECT
        CAST(LocksAcquired.TargetXml AS XML)  AS RBufXml
    INTO
        #XmlAsTable
    FROM
        (
        SELECT
                CAST(t.target_data AS XML)  AS TargetXml
            FROM
                     sys.dm_xe_session_targets  AS t
                JOIN sys.dm_xe_sessions         AS s

                    ON s.address = t.event_session_address
            WHERE
                t.target_name = 'ring_buffer'
                AND
                s.name        = 'ring_buffer_lock_acquired_4'
        )
            AS LocksAcquired;


SELECT * FROM #XmlAsTable;

XQuery to see the XML as a rowset

To see the preceding XML as a relational rowset, continue from the preceding SELECT statement by issuing the following T-SQL. The commented lines explain each use of XQuery.

SQL
SELECT
         -- (A)
         ObjectLocks.value('(@timestamp)[1]',
            'datetime'     )  AS [OccurredDtTm]

        -- (B)
        ,ObjectLocks.value('(data[@name="mode"]/text)[1]',
            'nvarchar(32)' )  AS [Mode]

        -- (C)
        ,ObjectLocks.value('(data[@name="transaction_id"]/value)[1]',
            'bigint' )  AS [TxnId]

        -- (D)
        ,ObjectLocks.value('(action[@name="database_name" and @package="sqlserver"]/value)[1]',
            'nvarchar(128)')  AS [DatabaseName]
    FROM
        #TableXmlCell
    CROSS APPLY
        -- (E)
        TargetDateAsXml.nodes('/RingBufferTarget/event[@name="lock_acquired"]')  AS T(ObjectLocks);

XQuery notes from preceding SELECT

(A)

  • timestamp= attribute's value, on <event> element.
  • The '(...)[1]' construct ensures only one value returned per iteration, as is a required limitation of the .value() XQuery method of XML data type variable and columns.

(B)

  • <text> element's inner value, within a <data> element which has its name= attribute equal to "mode".

(C)

  • <value> elements inner value, within a <data> element which has its name= attribute equal to "transaction_id".

(D)

  • <event> contains <action>.
  • <action> having name= attribute equal to "database_name", and package= attribute equal to "sqlserver" (not "package0"), get the inner value of <value> element.

(E)

  • C.A. causes processing to repeat for every individual <event> element which has its name= attribute equal to "lock_acquired".
  • This applies to the XML returned by the preceding FROM clause.

Output from XQuery SELECT

Next is the rowset generated by the preceding T-SQL, which includes XQuery.

OccurredDtTm              Mode    DatabaseName
------------              ----    ------------
2016-08-05 23:59:53.987   SCH_S   InMemTest2
2016-08-05 23:59:56.013   SCH_S   InMemTest2

XEvent .NET namespaces and C#

Package0 has two more targets, but they cannot be used in Transact-SQL:

  • compressed_history
  • event_stream

One way we know those two targets can't be used in T-SQL is that their non-null values in the column sys.dm_xe_objects.capabilities don't include the bit 0x1.

The event_stream target can be used in .NET programs written in languages like C#. C# and other .NET developers can access an event stream through a .NET Framework class, such as in namespace .Microsoft.SqlServer.XEvents.Linq

If encountered, error 25726 means the event stream filled up with data faster than the client could consume the data. This causes the database engine to disconnect from the event stream to avoid slowing the performance of the server.

XEvent namespaces