Specify file target filename dynamically

Posted on

Question :

I need to create an Extended Event session to capture all the executed queries while my server is running and save them in a file under a folder with the database name.

DECLARE @file varchar(50);
declare @path nvarchar(250);
SET @file = 'D:XE ' + DB_NAME()
set @path = 'D:XE ' + DB_NAME() + 'day';
EXECUTE master.dbo.xp_create_subdir @file
CREATE EVENT SESSION newSession1
ON SERVER
ADD EVENT sqlserver.sql_statement_completed
(    ACTION (sqlserver.sql_text, sqlserver.tsql_stack, 
     sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.username )
    WHERE ( sqlserver.database_name = 'School' )
    ),
ADD EVENT sqlserver.sql_statement_starting
(    ACTION (sqlserver.sql_text, sqlserver.tsql_stack,
     sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.username )
    WHERE ( sqlserver.database_name = 'School')    
    )
ADD target package0.event_file (SET filename = @path) -- problem
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=OFF)
GO

This code shows an error in set Filename = @path.

Answer :

You need to create the event session in dynamic SQL (or build the whole command in C#).

DECLARE @file nvarchar(500), @path nvarchar(500), @db sysname = DB_NAME(); 

SET @file = RTRIM(N'D:XE ') + @db;
SET @path = @file + N'day'; 

EXEC master.dbo.xp_create_subdir @file;

DECLARE @sql nvarchar(max) = N'CREATE EVENT SESSION ' + @db + N'_Session1 
  ON SERVER 
  ADD EVENT sqlserver.sql_statement_completed 
  (
    ACTION (sqlserver.sql_text, sqlserver.tsql_stack, sqlserver.client_app_name, 
            sqlserver.client_hostname, sqlserver.username 
  ) WHERE ( sqlserver.database_name = N''' + @db + N''' ) ),
  ADD EVENT sqlserver.sql_statement_starting 
  (
    ACTION (sqlserver.sql_text, sqlserver.tsql_stack, sqlserver.client_app_name, 
            sqlserver.client_hostname, sqlserver.username 
  ) WHERE ( sqlserver.database_name = N''' + @db + N''')
)
ADD target package0.event_file
(
  SET filename = N''' + @path + N'''
) 
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=OFF);';

EXEC master.sys.sp_executesql @sql;

Leave a Reply

Your email address will not be published.