sp_trace_generateevent (Transact-SQL)

适用于:SQL ServerAzure SQL 数据库Azure SQL 托管实例

创建用户定义事件。 可以使用 SQL 跟踪或扩展事件收集该事件

注意

此存储过程 弃用。 所有其他与 SQL 跟踪相关的存储过程都已弃用。

Transact-SQL 语法约定

语法

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

参数

[ @eventid = ] eventid

要触发的事件的 ID。 @eventid为 int,无默认值。 ID 必须介于非8291独占范围内。 此范围表示用户定义的事件。 在 SQL 跟踪中,使用 sp_trace_setevent 将此 ID 的事件添加到跟踪,以捕获从此存储过程触发的相同 ID 的事件。

[ @userinfo = ] 'userinfo'

可选的用户定义的字符串。 @userinfo为 nvarchar(128),默认值为 NULL.

[ @userdata = ] userdata

事件的可选用户定义数据。 @userdata为 varbinary(8000),默认值为 0x.

返回代码值

下表描述了用户在完成存储过程后可能会获取的返回代码值。

返回代码 说明
0 无错误。
1 未知错误。
3 指定的事件无效。 该事件可能不存在,或者它不适合存储过程。
13 内存不足。 当没有足够的内存来执行指定的操作时返回。

备注

若要使用 扩展事件捕获此存储过程触发的事件,请将 user_info 事件添加到事件会话。 有关详细信息,请参阅 CREATE EVENT 标准版SSION。 为 user_info 传递给 @eventid 参数的任何用户定义的事件 ID 值触发该事件。

只能将用户定义的事件的 ID 号用于 sp_trace_generateevent。 如果使用任何其他事件 ID 号,则会引发错误。

此存储过程的参数严格类型化。 如果传递给参数的值的数据类型与其说明中指定的参数数据类型不匹配,则存储过程将返回错误。

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"}]