Share via

Dynamic SQL for execute ALTER EVENT SESSION

Alen Cappelletti 1,047 Reputation points
2022-04-30T22:36:28.6+00:00

Hi all, but ALTER EVENT SESSION command could by be a dynamic statements?
'Cause I got always err...
You need first.. a Login "Extended Event".

DECLARE @Path nvarchar(200)
SET @Path = N'C:\Traces\aaa.xel'
;
DECLARE @SQLString NVARCHAR(500);   
SET @SQLString = N'
ALTER EVENT SESSION [Logins] ON SERVER 
ADD TARGET package0.event_file (SET filename=N''' + @Path + ''' , max_file_size=100, max_rollover_files = 100)'
;
EXEC @SQLString
;

err is...

Msg 203, Level 16, State 2, Line 25
The name '
ALTER EVENT SESSION [Logins] ON SERVER
ADD TARGET package0.event_file (SET filename=N'C:\Traces\aaa.xel' , max_file_size=100, max_rollover_files = 100)' is not a valid identifier.

Alen

Developer technologies | Transact-SQL
Developer technologies | Transact-SQL

A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.

0 comments No comments

Answer accepted by question author

Dan Guzman 9,516 Reputation points
2022-04-30T23:10:24.807+00:00

Enclose the variable in parenthesis so that the value is not interpreted as a stored procedure name:

EXEC (@SQLString);

Alternatively, use sp_executesql:

EXEC sp_executesql @SQLString;

Was this answer helpful?

1 person found this answer helpful.

2 additional answers

Sort by: Most helpful
  1. Erland Sommarskog 134.7K Reputation points MVP Volunteer Moderator
    2022-05-01T09:24:47.24+00:00

    In addition to Dan's post, this is what EXEC @VAR without parens means:

       DECLARE  @var sysname = 'sp_who'  
       EXEC @var  
    

    That is, execute the stored procedure of which the name is in @VAR .

    Was this answer helpful?

    1 person found this answer helpful.

  2. Bert Zhou-msft 3,521 Reputation points
    2022-05-02T03:44:21.4+00:00

    Hi,@Alen Cappelletti

    Welcome to Microsoft T-SQL Q&A Forum!

    Have you tried this?

    EXEC master.sys.sp_executesql @sqlString;  
    

    Best regards,
    Bert Zhou


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.