英文原帖:
除了以上回复的全面的答案,有时以编程方式访问执行计划会很有用。示例代码如下:
DECLARE @TraceID INTEXEC StartCapture @@SPID, @TraceID OUTPUTEXEC sp_help 'sys.objects' /*<-- Call your stored proc of interest here.*/EXEC StopCapture @TraceID
示例StartCapture定义
CREATE PROCEDURE StartCapture@Spid INT,@TraceID INT OUTPUTASDECLARE @maxfilesize BIGINT = 5DECLARE @filepath NVARCHAR(200) = N'C:\trace_' + LEFT(NEWID(),36)EXEC sp_trace_create @TraceID OUTPUT, 0, @filepath, @maxfilesize, NULLexec sp_trace_setevent @TraceID, 122, 1, 1exec sp_trace_setevent @TraceID, 122, 22, 1exec sp_trace_setevent @TraceID, 122, 34, 1exec sp_trace_setevent @TraceID, 122, 51, 1exec sp_trace_setevent @TraceID, 122, 12, 1-- filter for spidEXEC sp_trace_setfilter @TraceID, 12, 0, 0, @Spid-- start the traceEXEC sp_trace_setstatus @TraceID, 1
示例StopCapture定义
CREATE PROCEDURE StopCapture@TraceID INTASWITH XMLNAMESPACES ('http://schemas.microsoft.com/sqlserver/2004/07/showplan' as sql),CTEas (SELECT CAST(TextData AS VARCHAR(MAX)) AS TextData,ObjectID,ObjectName,EventSequence,/*costs accumulate up the tree so the MAX should be the root*/MAX(EstimatedTotalSubtreeCost) AS EstimatedTotalSubtreeCostFROM fn_trace_getinfo(@TraceID) fnCROSS APPLY fn_trace_gettable(CAST(value AS NVARCHAR(200)), 1)CROSS APPLY (SELECT CAST(TextData AS XML) AS xPlan) xCROSS APPLY (SELECT T.relop.value('@EstimatedTotalSubtreeCost','float') AS EstimatedTotalSubtreeCostFROM xPlan.nodes('//sql:RelOp') T(relop)) caWHERE property = 2AND TextData IS NOT NULLAND ObjectName not in ( 'StopCapture', 'fn_trace_getinfo' )GROUP BY CAST(TextData AS VARCHAR(MAX)),ObjectID,ObjectName,EventSequence)SELECT ObjectName,SUM(EstimatedTotalSubtreeCost) AS EstimatedTotalSubtreeCostFROM CTEGROUP BY ObjectID,ObjectName-- Stop the traceEXEC sp_trace_setstatus @TraceID, 0-- Close and delete the traceEXEC sp_trace_setstatus @TraceID, 2GO