sp_trace_generateevent (Transact-SQL)

適用於:SQL ServerAzure SQL DatabaseAzure SQL 受控執行個體

建立使用者定義事件。 您可以使用 SQL 追蹤或擴充事件來收集事件

注意

此預存程式 過時。 所有其他 SQL 追蹤相關預存程式都已被取代。

Transact-SQL 語法慣例

語法

sp_trace_generateevent
    [ @eventid = ] eventid
    [ , [ @userinfo = ] N'userinfo' ]
    [ , [ @userdata = ] userdata ]
[ ; ]

引數

[ @eventid = ] eventid

要引發之事件的標識碼。 @eventid為 int,沒有預設值。 標識碼必須介於 從 82 內含到 91 的範圍內。 此範圍代表使用者定義事件。 在 SQL 追蹤中,使用 sp_trace_setevent 將具有此標識符的事件新增至追蹤,以擷取從這個預存程式引發的相同標識碼的事件。

[ @userinfo = ] 'userinfo'

選擇性的使用者定義字串。 @userinfo為 nvarchar(128),預設值為 NULL

[ @userdata = ] userdata

事件的選擇性使用者定義數據。 @userdata為 varbinary(8000),預設值為 0x

傳回碼值

下表描述使用者可能會在預存程式完成之後取得的傳回碼值。

傳回碼 描述
0 沒有錯誤。
1 未知的誤差。
3 指定的事件無效。 事件可能不存在,或不適合預存程式。
13 記憶體不足。 當記憶體不足而無法執行指定的動作時傳回。

備註

若要使用 擴充事件擷取這個預存程序引發的事件,請將 user_info 事件新增至事件會話。 如需詳細資訊,請參閱 CREATE EVENT SESSION。 針對 user_info 傳遞至 @eventid 參數的任何使用者定義事件標識碼,會引發事件。

只能搭配 sp_trace_generateevent使用使用者定義事件的標識碼。 如果使用任何其他事件標識碼,就會引發錯誤。

這個預存程式的參數會嚴格輸入。 如果傳遞至參數之值的數據類型不符合其描述中指定的參數數據類型,預存程式會傳回錯誤。

sp_trace_generateevent 會執行許多先前由擴充預存程式執行的 xp_trace_* 動作。 使用 sp_trace_generateevent 取代 xp_trace_generate_event

權限

在 SQL Server 和 Azure SQL 受控執行個體 中,需要 ALTER TRACE 許可權。 在 Azure SQL 資料庫 中,需要資料庫角色的成員public資格。

範例

下列範例會在將數據列插入數據表時引發使用者定義的事件。 事件包含插入數據表的數據。

若要收集此範例引發的事件, 請建立擴充事件會話 並包含 user_info 事件,或 建立 SQL 追蹤 並包含 UserConfigurable:0 事件。

-- Create a table
DROP TABLE IF EXISTS dbo.user_defined_event_example;

CREATE TABLE dbo.user_defined_event_example
(
Id int IDENTITY(1,1) PRIMARY KEY,
Data nvarchar(60) NOT NULL
);

DROP TRIGGER IF EXISTS fire_user_defined_event;
GO

-- Create an insert trigger on the table
CREATE TRIGGER fire_user_defined_event ON dbo.user_defined_event_example
FOR INSERT
AS
DECLARE @EventData varbinary(8000);

-- Convert inserted rows to JSON and cast it as a binary value
SELECT @EventData = CAST((
                         SELECT Id, Data
                         FROM inserted
                         FOR JSON AUTO
                         ) AS varbinary(8000));

-- Fire the event with the payload carrying inserted rows as JSON
EXEC dbo.sp_trace_generateevent
    @eventid = 82,
    @userinfo = N'Inserted rows into dbo.user_defined_event_example',
    @userdata = @EventData;
GO

-- Insert a row into the table. The trigger fires the event.
INSERT INTO dbo.user_defined_event_example (Data)
VALUES (N'Example data');

-- Copy the binary payload from the event and cast it to a string with the JSON value
SELECT CAST(0x5B007B0022004900640022003A0031002C002200440061007400610022003A0022004500780061006D0070006C0065002000640061007400610022007D005D00 AS nvarchar(max));
-- This returns: [{"Id":1,"Data":"Example data"}]