会话可以捕获所有执行的SQL语句,但是这样捕获的数据量太大,所以要进行一些筛选。比如账号,DB,影响行数。
查询的结果建议插入实体表,万一SSMS会话出现问题,零时表数据消失,还得重新查询,时间太久了。
row_count 是整个存储的插入查询总数
EventTime是SQL执行完成时的时间点,
duration单位是微秒 1s=1000000us
select LEFT(SWITCHOFFSET(n.value('@timestamp','Datetime'),'+08:00'),23) as EventTime, n.value('(data[@name="row_count"]/value)[1]', 'bigint') as row_count, n.value('(data[@name="duration"]/value)[1]', 'bigint') as duration, n.value('(data[@name="statement"]/value)[1]', 'nvarchar(max)') as statement, n.value('(action[@name="database_name"]/value)[1]', 'nvarchar(128)') as database_name, n.value('(action[@name="client_app_name"]/value)[1]', 'nvarchar(128)') as client_app_name, n.value('(action[@name="username"]/value)[1]', 'nvarchar(128)') as username, n.value('(action[@name="client_hostname"]/value)[1]', 'nvarchar(128)') as client_hostname into #tmp from (select cast(event_data as XML) as event_data from sys.fn_xe_file_target_read_file('M:XEventDB_Usage_0*.xel', null, null, null)) ed cross apply ed.event_data.nodes('event') as q(n) order by EventTime desc select * from #tmp
生成的xel文件,建议最大就是1G,1G的解析时间大概20分钟,而10G要解析8个多小时,文件的修改时间为最后写入的时间(不是创建的时间),以此来判断需要解析哪些文件。
CREATE EVENT SESSION [DB_Usage] ON SERVER ADD EVENT sqlserver.sql_statement_completed(SET collect_statement=(1) ACTION(sqlserver.client_app_name,sqlserver.client_hostname,sqlserver.
database_name,sqlserver.nt_username,sqlserver.sql_text,sqlserver.username)) ADD TARGET package0.event_file(SET filename=N'D:XEventDB_Usage.xel') WITH (MAX_MEMORY=4096 KB,EVENT_RETENTION_MODE=ALLOW_SINGLE_EVENT_LOSS,
MAX_DISPATCH_LATENCY=30 SECONDS,MAX_EVENT_SIZE=0 KB,MEMORY_PARTITION_MODE=NONE,TRACK_CAUSALITY=OFF,STARTUP_STATE=ON) GO