是否可以将统计结果保存到表格中?

Faj*_*iya 1 sql-server execution-plan

在 SQL Server 中,我们可以使用它set statistics profile on来启用会话分析。然后您可以执行任何一条语句,相应的执行计划将以表格形式显示。是否可以将这种流行的表单计划保存到某个表中,以便我可以对其进行过滤?

此平板电脑表单执行计划的示例如下所示: 在此输入图像描述

Dan*_*man 5

的输出set statistics profile on在正常查询结果(如果有)之后作为结果集返回到客户端应用程序。这可以由客户端应用程序(如您问题中的 SSMS)捕获,但不能由 T-SQL 代码捕获。

下面是一个 PowerShell 示例,它执行查询并将STATISTICS PROFILE ON统计配置文件结果插入到表中以满足临时需求。

$query = @"
SET STATISTICS PROFILE ON;
SELECT * FROM dbo.YourTable;
"@

$connectionString = "Data Source=.;Initial Catalog=YourDatabase;Integrated Security=SSPI"
$connection = New-Object System.Data.SqlClient.SqlConnection($connectionString)
try
{
    $connection.Open()
    $command = New-Object System.Data.SqlClient.SqlCommand($query, $connection)
    $queryResults = New-Object System.Data.DataTable
    $statisticsProfileResults = New-Object System.Data.DataTable
    $reader = $command.ExecuteReader()

    # get query results (first result set)
    $queryResults.Load($reader)

    # get stats profile results (second result set)
    $statisticsProfileResults.Load($reader)

    $reader.Close()

    # insert stats profile results into table
    $bcp = New-Object System.Data.SqlClient.SqlBulkCopy($connection)
    $bcp.DestinationTableName = "dbo.statistics_profile"
    $bcp.WriteToServer($statisticsProfileResults)
}
finally
{
    if ($reader -ne $null) { $reader.Dispose() }
    if ($command -ne $null) { $command.Dispose() }
    if ($bcp -ne $null) { $bcp.Dispose() }
    if ($connection -ne $null) { $connection.Dispose() }
}
Run Code Online (Sandbox Code Playgroud)

统计资料表的 DDL:

CREATE TABLE dbo.statistics_profile(
      Rows bigint NOT NULL  
    , Executes bigint NOT NULL
    , StmtText nvarchar(MAX)  NOT NULL
    , StmtId int  NOT NULL
    , NodeId int  NOT NULL
    , Parent int  NOT NULL
    , PhysicalOp sysname NULL
    , LogicalOp sysname NULL
    , Argument  nvarchar(MAX) NULL
    , DefinedValues nvarchar(MAX) NULL  
    , EstimateRows real NULL
    , EstimateIO real NULL
    , EstimateCPU real NULL
    , AvgRowSize int NULL
    , TotalSubtreeCost real NULL
    , OutputList nvarchar(MAX)  NULL
    , Warnings nvarchar(MAX)  NULL  
    , Type  sysname NULL
    , Parallel bit  NULL
    , EstimateExecutions real NULL
);
Run Code Online (Sandbox Code Playgroud)