Create procedure [DBO]. [sptracemysessionstart] @ spid int As -- Create a queue Declare @ RC int Declare @ traceid int Declare @ maxfilesize bigint Set @ maxfilesize = 5 Declare @ filename nvarchar (245) Set @ filename = 'C: \ tracemysession _' + Convert (nvarchar (10), @ spid) + '_ D' + Replace (convert (varchar, getdate (), 111 ),'/','') + Replace (convert (varchar, getdate (), 108 ),':','') Exec @ rc = sp_trace_create @ traceid output, 2, @ filename, @ maxfilesize, Null If (@ RC! = 0) goto Error -- Set the events Declare @ on Bit Set @ on = 1 Exec sp_trace_setevent @ traceid, 12, 1, @ on Exec sp_trace_setevent @ traceid, 12, 12, @ on Exec sp_trace_setevent @ traceid, 12, 14, @ on -- Set the filters Declare @ intfilter int Declare @ bigintfilter bigint Exec sp_trace_setfilter @ traceid, 12, 1, 0, @ spid -- Set the trace status to start Exec sp_trace_setstatus @ traceid, 1 -- Display trace ID for future references Select traceid = @ traceid Goto finish Error: Select errorcode = @ RC Finish: Stop a trail Once you complete the tracking, the following stored procedure will stop and turn it off. If this fails, the server-side tracing will continue to run and collect any other session data that exactly has the same spid. This stored procedure excluded a parameter, that is, traceid. When you run the first stored procedure, it will give you the traceid you created. This is the value that you pass to the second stored procedure so that the trail is stuck and disabled. I also created it in my primary database, but you can also create it in any different database.
Create procedure [DBO]. [sptracemysessionstop] @ traceid intAs Exec sp_trace_setstatus @ traceid, 0 Exec sp_trace_setstatus @ Traceid, 2 |
Let's try it. Therefore, we can assume that we want to run the following code.
Exec Master. DBO. sptracemysessionstart 52Use adventureworks Go Select name From SYS. sysobjects where xtype = 'U' Go Select top 10 Title From HumanResources. Employee Go Exec master. DBO. sptracemysessionstop 2 |
First, we need to start this trail, that is, the first line in my script. I can see my spid at the bottom, that is, 52, which has been highlighted in the following. Figure 1 When I run this stored procedure, the output result shows traceid, that is, "2 ". We need to save this value for later use. Figure 2 After I run other commands and all of them are complete, I can run the following command to stop and turn off this trace and use the traceid value "2" we obtained above ". Figure 3 View the captured If I use the probe to open the file we created, I can see all the commands run in my sessions. You can copy these commands to a query window to reuse them. Figure 4 Another option is to download a file created to the SQL Server table or use SQL Server to query only the data. Figure 5
Select textdata, starttime From: fn_trace_gettable ('C: \ tracemysession_52_d20090317120542.trc ', Default) Where textdata is not null |
|