在Microsoft SQL Server如何获得查询/存储过程的查询执行计划?


当前回答

在SQL Server Management Studio:

“Ctrl + M”将生成实际执行计划

“Ctrl + L”将生成估计执行计划

“Shift + Alt + S”为客户端统计

“Ctrl + Alt + P”用于SQL Server Profiler中的跟踪查询。

其他回答

您也可以通过powershell使用SET STATISTICS XML ON来获得实际的计划。我写它是为了将多语句计划合并为一个计划;

    ########## BEGIN : SCRIPT VARIABLES #####################
    [string]$server = '.\MySQLServer'
    [string]$database = 'MyDatabase'
    [string]$sqlCommand = 'EXEC sp_ExampleSproc'
    [string]$XMLOutputFileName = 'sp_ExampleSproc'
    [string]$XMLOutputPath = 'C:\SQLDumps\ActualPlans\'
    ########## END   : SCRIPT VARIABLES #####################

    #Set up connection
    $connectionString = "Persist Security Info=False;Integrated Security=true;Connection Timeout=0;Initial Catalog=$database;Server=$server"
    $connection = new-object system.data.SqlClient.SQLConnection($connectionString)

    #Set up commands
    $command = new-object system.data.sqlclient.sqlcommand($sqlCommand,$connection)
    $command.CommandTimeout = 0
    $commandXMLActPlanOn = new-object system.data.sqlclient.sqlcommand("SET STATISTICS XML ON",$connection)
    $commandXMLActPlanOff = new-object system.data.sqlclient.sqlcommand("SET STATISTICS XML OFF",$connection)

    $connection.Open()

    #Enable session XML plan
    $result = $commandXMLActPlanOn.ExecuteNonQuery()

    #Execute SP and return resultsets into a dataset
    $adapter = New-Object System.Data.sqlclient.sqlDataAdapter $command
    $dataset = New-Object System.Data.DataSet
    $adapter.Fill($dataSet) | Out-Null

    #Set up output file name and path
    [string]$fileNameDateStamp = get-date -f yyyyMMdd_HHmmss
    [string]$XMLOutputFilePath = "$XMLOutputPath$XMLOutputFileName`_$fileNameDateStamp.sqlplan"

    #Pull XML plans out of dataset and merge into one multi-statement plan
    [int]$cntr = 1
    ForEach($table in $dataset.Tables)
    {
            if($table.Columns[0].ColumnName -eq "Microsoft SQL Server 2005 XML Showplan")
            {

                [string]$fullXMLPlan = $Table.rows[0]."Microsoft SQL Server 2005 XML Showplan"

                if($cntr -eq 1)
                    {

                    [regex]$rx = "\<ShowPlanXML xmlns\=.{1,}\<Statements\>"
                    [string]$startXMLPlan = $rx.Match($fullXMLPlan).Value
                    [regex]$rx = "\<\/Statements\>.{1,}\<\/ShowPlanXML\>"
                    [string]$endXMLPlan = $rx.Match($fullXMLPlan).Value

                    $startXMLPlan | out-file -Append -FilePath $XMLOutputFilePath

                    }

                [regex]$rx = "\<StmtSimple.{1,}\<\/StmtSimple\>"
                [string]$bodyXMLPlan = $rx.Match($fullXMLPlan).Value

                $bodyXMLPlan | out-file -Append -FilePath $XMLOutputFilePath

                $cntr += 1
            } 
    }

    $endXMLPlan | out-file -Append -FilePath $XMLOutputFilePath

    #Disable session XML plan
    $result = $commandXMLActPlanOff.ExecuteNonQuery()

    $connection.Close()

从SQL Server 2016+开始,引入了查询存储功能来监控性能。它提供了对查询计划选择和性能的洞察。 它并不是跟踪或扩展事件的完全替代,但随着它从一个版本到另一个版本的发展,我们可能会在SQL Server的未来版本中得到一个功能齐全的查询存储。 查询存储的主要流程

SQL Server existing components interact with query store by utilising Query Store Manager. Query Store Manager determines which Store should be used and then passes execution to that store (Plan or Runtime Stats or Query Wait Stats) Plan Store - Persisting the execution plan information Runtime Stats Store - Persisting the execution statistics information Query Wait Stats Store - Persisting wait statistics information. Plan, Runtime Stats and Wait store uses Query Store as an extension to SQL Server.

Enabling the Query Store: Query Store works at the database level on the server. Query Store is not active for new databases by default. You cannot enable the query store for the master or tempdb database. Available DMV sys.database_query_store_options (Transact-SQL) Collect Information in the Query Store: We collect all the available information from the three stores using Query Store DMV (Data Management Views). Query Plan Store: Persisting the execution plan information and it is accountable for capturing all information that is related to query compilation. sys.query_store_query (Transact-SQL) sys.query_store_plan (Transact-SQL) sys.query_store_query_text (Transact-SQL) Runtime Stats Store: Persisting the execution statistics information and it is probably the most frequently updated store. These statistics represent query execution data. sys.query_store_runtime_stats (Transact-SQL) Query Wait Stats Store: Persisting and capturing wait statistics information. sys.query_store_wait_stats (Transact-SQL)

注意:查询等待统计数据存储仅在SQL Server 2017+中可用

与SQL Server Management Studio(已经解释过了)一样,Datagrip也可以在这里解释。

右键单击SQL语句,并选择Explain plan。 在Output窗格中,单击Plan。 默认情况下,您将看到查询的树表示形式。去看 查询计划时,单击“显示可视化”图标,或按 Ctrl + Shift + Alt + U

解释执行计划可能会非常详细,并占用大量阅读时间,但总的来说,如果你在查询之前使用'explain',它应该会给你很多信息,包括哪些部分首先执行等等。 如果你想了解更多关于这方面的细节,我写了一篇关于这方面的小博客,它也会给你指明正确的裁判。 https://medium.com/swlh/jetbrains-datagrip-explain-plan-ac406772c470

除了前面回答中描述的方法外,您还可以使用免费的执行计划查看器和查询优化工具ApexSQL plan(我最近碰到了它)。

您可以将ApexSQL计划安装并集成到SQL Server Management Studio中,因此可以直接从SSMS查看执行计划。

在“ApexSQL计划”中查看估计的执行计划

单击SSMS中的新建查询按钮,并将查询文本粘贴到查询文本窗口中。右击并从上下文菜单中选择“Display Estimated Execution Plan”选项。

执行计划图将显示在结果部分的execution plan选项卡中。接下来右键单击执行计划,在上下文菜单中选择“在ApexSQL计划中打开”选项。

预估执行计划将在ApexSQL plan中打开,可以对其进行分析以进行查询优化。

在“ApexSQL计划”中查看实际执行计划

要查看查询的实际执行计划,从前面提到的第二步继续,但是现在,一旦估计计划显示出来,在ApexSQL计划的主带栏中单击“实际”按钮。

一旦点击“实际”按钮,实际执行计划将显示详细的成本参数预览以及其他执行计划数据。

点击此链接可以找到有关查看执行计划的更多信息。