Merge pull request #15 from microsoft/v6.24.02.18

Release version v6.24.02.18
This commit is contained in:
JosephPilov-MSFT 2024-02-16 18:22:52 -06:00 коммит произвёл GitHub
Родитель 74af3ed373 778f4bea69
Коммит ac483ee181
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: B5690EEEBB952194
45 изменённых файлов: 10118 добавлений и 5113 удалений

1
.gitignore поставляемый
Просмотреть файл

@ -26,7 +26,6 @@ x86/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/

Просмотреть файл

@ -212,6 +212,7 @@ Possible values are:
- IO
- LightPerf
- ProcessMonitor
- NeverEndingQuery
- MenuChoice - this directs SQL LogScout to present an interactive menu with Scenario choices. The option is available in cases where multiple parameters are used with SQL_LogScout.cmd. Combining MenuChoice with another scenario choice, causes SQL LogScout to ignore MenuChoice and pick the selected scenario(s). For more information on what data each scenario collects, see [Scenarios](#scenarios)
- NoBasic - this instructs SQL LogScout to skip the collection of basic logs, when Basic scenario is part of another scenario by default. For example if you use GeneralPerf+NoBasic, only the performance logs will be collected and static logs (Basic) will be skipped. If NoBasic+Basic is specified by mistake, the assumption is you intend to collect data; therefore Basic is enabled and NoBasic flag is disabled. Similarly, if NoBasic+Basic+A_VALID_SCENARIO is selected, again the assumption is that data collection is intended. In this case, Basic is enabled, NoBasic is disabled and A_VALID_SCENARIO will collect Basic logs.
@ -255,6 +256,9 @@ Possible values are:
- Quiet - suppresses possible prompts for data input. Selecting Quiet mode implicitly selects "Y" to all the screens that requires an agreement to proceed.
- Noisy - (default) shows prompts requesting user input where necessary
### DisableCtrlCasInput
Used for internal testing only and changes behavior of cancelling SQL LogScout. Do not use this parameter.
## Graphical User Interface (GUI)
The GUI is a feature added in version 5.0 of SQL LogScout. It allows the user to make many of the selections in a single user interface, if they prefer it over the menu options in command prompt. You can do the following in the GUI:
@ -330,16 +334,20 @@ Collects snapshot or static logs. It captures information on:
- OS disk information
- Running filter drivers
- Event logs (system and application in both .CSV and .TXT formats)
- SQL Server dumps found in the errorlog directory. We collect up to 20 dumps if they were created in the last 2 months and are less than 100 MB in size.
- Memory dump .txt files (most recent 200 files)
- IPConfig, DNSClientInfo, and TCP and UDP endpoints
- SQL Errorlogs
- SQL Agent logs
- SystemHealth XELs
- Polybase logs
- Azure Arc Agent logs (if SQL Server enabled for Azure Arc)
- Azure Arc Agent logs (if SQL Server enabled for Azure Arc). More info available at [Azure Instance Metadata Service](https://learn.microsoft.com/en-us/azure/virtual-machines/instance-metadata-service?tabs=windows)
- [SQL Azure VM Information](https://learn.microsoft.com/azure/virtual-machines/instance-metadata-service?tabs=windows) (if SQL Server is Azure Virtual Machine)
- Performance Monitor counters for SQL Server instance and general OS counters - just a few snapshots for a few seconds.
- [AlwaysOn_health.xel](https://docs.microsoft.com/sql/database-engine/availability-groups/windows/always-on-extended-events#bkmk_alwayson_health)
- [MSSQLSERVER_SQLDIAG.xel](https://docs.microsoft.com/sql/database-engine/availability-groups/windows/always-on-health-diagnostics-log)
- [SQL VSS Writer Log (SQL Server 2019 and later)](https://docs.microsoft.com/sql/relational-databases/backup-restore/sql-server-vss-writer-logging)
- [SQL Assessment API](https://docs.microsoft.com/sql/tools/sql-assessment-api/sql-assessment-api-overview) log
- Environment variables full list
## 1. GeneralPerf scenario
@ -353,7 +361,6 @@ Collects all the Basic scenario logs as well as some long-term, continuous logs
- Query Data Store (QDS) info (if that is active)
- Tempdb contention info from SQL DMVs/system views
- Linked Server metadata (SQL DMVs/system views)
- Service Broker configuration information (SQL DMVs/system views)
*Note:* If you combine GeneralPerf with DetailedPerf scenario, then the GeneralPerf will be disabled and only DetailedPerf will be collected.
@ -377,6 +384,7 @@ Collects all the Basic scenario logs as well as Always On configuration informat
- Basic scenario
- Always On diagnostic info (SQL DMVs/system views)
- [AlwaysOn_health.xel](https://docs.microsoft.com/sql/database-engine/availability-groups/windows/always-on-extended-events#bkmk_alwayson_health)
- Always On [Data Movement Latency Xevent ](https://techcommunity.microsoft.com/t5/sql-server-support/troubleshooting-data-movement-latency-between-synchronous-commit/ba-p/319141) and the AG topology XML file required for [AG latency](https://learn.microsoft.com/archive/blogs/psssql/aglatency-report-tool-introduction) analysis.
- Core Xevents trace (RPC and Batch started and completed, login/logout, errors)
- Performance Monitor counters for SQL Server instance and general OS counters
@ -448,6 +456,27 @@ Collects everything that the GeneralPerf scenario does (includes Basic scenario)
Collects a [Process Monitor](https://docs.microsoft.com/en-us/sysinternals/downloads/procmon) (Procmon) log to help with troubleshooting specific file or registry related issues. This collector requires that you have Procmon downloaded and unzipped in a folder of your choice. SQL LogScout will prompt you to provide the path to that folder. You don't need to wrap the path in quotes even if there are spaces in the path name.
## 14. Service Broker and Database mail
Collect logs to help troubleshoot SQL Service Broker and Database mail scenarios. The scenarion includes the following logs:
- Basic scenario
- Service Broker configuration information (SQL DMVs/system views)
- Performance Monitor counters for SQL Server instance and general OS counters
- Extended events (Xevents) for SQL Server Service Broker
## 15. Never Ending Query
Collect logs to help troubleshoot Never Ending Query scenarios. The scenario includes the following logs:
- Basic scenario
- Never Ending Query Perfstats (SQL DMVs/system views)
- Performance Monitor counters for SQL Server instance and general OS counters
- XML Plans for top 5 High CPU consuming queries
- XML Plans for all Never Ending queries
A never-ending query is considered a query that is driving CPU due to execution for a long time, and not one that is waiting for a long-time. This scenario will consider only queries that have consumed 60 seconds of more of CPU time. For more information, see [Troubleshoot queries that seem to never end in SQL Server](https://learn.microsoft.com/en-us/troubleshoot/sql/database-engine/performance/troubleshoot-never-ending-query)
# Output folders
**Output folder**: All the diagnostic log files are collected in the \output (or \output_ddMMyyhhmmss) folder. These include Perfmon log (.BLG), event logs, system information, extended event (.XEL), etc. By default this folder is created in the same location where SQL LogScout files reside (present directory). However a user can choose to collect data on a different disk volume and folder. This can be done by following the prompt for a non-default drive and directory or by using the CustomOutputPath parameter ([Parameters](#parameters))
@ -504,6 +533,8 @@ Diagnostic data is collected from the SQL instance you selected locally on the m
# Security
## Digitally signed files and hash computed
SQL LogScout is released with digitally-signed Powershell files. For other files, SQL LogScout calculates a SHA512 hash and compares it to the expected value of each file. If the stored hash does not match the calculated hash on disk, then SQL LogScout will not run.
To manually validate script signature, you may execute the following:
@ -548,6 +579,10 @@ SignerCertificate : [Subject]
ABDCA79AF9DD48A0EA702AD45260B3C03093FB4B
```
## Encrypted connection to SQL Server
SQL LogScout negotiates connection encryption with the SQL Server it collects data from. It does so by using "Encrypt=True;TrustServerCertificate=true;" and "sqlcmd -C -N" values.
# Sample output
```bash
@ -642,10 +677,9 @@ Copyright (c) 2021 Microsoft Corporation. All rights reserved.
2021-09-10 11:04:21.313 INFO Executing Collector: HighCPU_perfstats
2021-09-10 11:04:21.364 INFO Executing Collector: SQLServerPerfStats
2021-09-10 11:04:23.441 INFO Executing Collector: SQLServerPerfStatsSnapshotStartup
2021-09-10 11:04:23.492 INFO Executing Collector: Query Store
2021-09-10 11:04:23.492 INFO Executing Collector: QueryStore
2021-09-10 11:04:25.552 INFO Executing Collector: TempDBAnalysis
2021-09-10 11:04:25.601 INFO Executing Collector: linked_server_config
2021-09-10 11:04:25.652 INFO Executing Collector: SSB_diag
2021-09-10 11:04:25.708 INFO Collecting logs for 'AlwaysOn' scenario
2021-09-10 11:04:25.740 INFO Executing Collector: AlwaysOnDiagScript
2021-09-10 11:04:25.788 INFO Executing Collector: Xevent_CoreAddSesion
@ -678,7 +712,7 @@ Copyright (c) 2021 Microsoft Corporation. All rights reserved.
2021-09-10 11:04:47.407 INFO Executing Collector: FLTMC_Filters
2021-09-10 11:04:47.464 INFO Executing Collector: FLTMC_Instances
2021-09-10 11:04:47.533 INFO Executing Collector: SystemInfo_Summary
2021-09-10 11:04:47.618 INFO Executing Collector: MiscPssdiagInfo
2021-09-10 11:04:47.618 INFO Executing Collector: MiscDiagInfo
2021-09-10 11:04:47.681 INFO Executing Collector: SQLErrorLogs_AgentLogs_SystemHealth_MemDumps_FciXel
2021-09-10 11:04:50.501 INFO Executing Collector: PolybaseLogs
2021-09-10 11:04:50.533 INFO Executing Collector: SQLAssessmentAPI

Просмотреть файл

@ -135,7 +135,7 @@ function Set-NewOutputPath
try
{
[string] $new_output_folder_name = "_" + @(Get-Date -Format ddMMyyhhmmss) + "\"
[string] $new_output_folder_name = "_" + @(Get-Date -Format yyyyMMddTHHmmss) + "\"
$global:output_folder = $global:output_folder.Substring(0, ($global:output_folder.Length-1)) + $new_output_folder_name
}
catch
@ -238,7 +238,7 @@ function ReuseOrRecreateOutputFolder()
Write-LogWarning "It appears that output folder '$global:output_folder' has been used before."
Write-LogWarning "You can choose to:"
Write-LogWarning " - Delete (d) the \output folder contents and recreate it"
Write-LogWarning " - Create a new (n) folder using '\Output_ddMMyyhhmmss' format. You can manually delete this folder in the future"
Write-LogWarning " - Create a new (n) folder using '\Output_yyyyMMddTHHmmss' format. You can manually delete this folder in the future"
while (-not(($DeleteOrNew -eq "D") -or ($DeleteOrNew -eq "N")))
{
@ -283,9 +283,9 @@ function ReuseOrRecreateOutputFolder()
elseif ($DeleteOrNew -eq "N")
{
#these two calls updates the two globals for the new output and internal folders using the \Output_ddMMyyhhmmss format.
#these two calls updates the two globals for the new output and internal folders using the \Output_yyyyMMddTHHmmss format.
# [string] $new_output_folder_name = "_" + @(Get-Date -Format ddMMyyhhmmss) + "\"
# [string] $new_output_folder_name = "_" + @(Get-Date -Format yyyyMMddTHHmmss) + "\"
# $global:output_folder = $global:output_folder.Substring(0, ($global:output_folder.Length-1)) + $new_output_folder_name
Set-NewOutputPath
@ -416,7 +416,10 @@ function StartNewProcess()
Write-LogDebug "inside" $MyInvocation.MyCommand
[console]::TreatControlCAsInput = $true
if ($global:gDisableCtrlCasInput -eq "False")
{
[console]::TreatControlCAsInput = $true
}
try
{
@ -490,12 +493,442 @@ function StartNewProcess()
}
# fucntion to collect SQL SERVERPROPERTY and cahe it in $global:SQLSERVERPROPERTYTBL
# if globla variable is populated it will use it.
function getServerproperty()
{
Write-LogDebug "inside " $MyInvocation.MyCommand
$SQLSERVERPROPERTYTBL = @{}
[String] $query
if ($global:SQLSERVERPROPERTYTBL.Count -gt 0) {
Write-LogDebug "SQLSERVERPROPERTYTBL cached " -DebugLogLevel 2
return $global:SQLSERVERPROPERTYTBL
}
$properties = "BuildClrVersion",
"Collation",
"CollationID",
"ComparisonStyle",
"ComputerNamePhysicalNetBIOS",
"Edition",
"EditionID",
"EngineEdition",
"FilestreamConfiguredLevel",
"FilestreamEffectiveLevel",
"FilestreamShareName",
"HadrManagerStatus",
"InstanceDefaultBackupPath",
"InstanceDefaultDataPath",
"InstanceDefaultLogPath",
"InstanceName",
"IsAdvancedAnalyticsInstalled",
"IsBigDataCluster",
"IsClustered",
"IsExternalAuthenticationOnly",
"IsExternalGovernanceEnabled",
"IsFullTextInstalled",
"IsHadrEnabled",
"IsIntegratedSecurityOnly",
"IsLocalDB",
"IsPolyBaseInstalled",
"IsServerSuspendedForSnapshotBackup",
"IsSingleUser",
"IsTempDbMetadataMemoryOptimized",
"IsXTPSupported",
"LCID",
"LicenseType",
"MachineName",
"NumLicenses",
"PathSeparator",
"ProcessID",
"ProductBuild",
"ProductBuildType",
"ProductLevel",
"ProductMajorVersion",
"ProductMinorVersion",
"ProductUpdateLevel",
"ProductUpdateReference",
"ProductVersion",
"ResourceLastUpdateDateTime",
"ResourceVersion",
"ServerName",
"SqlCharSet",
"SqlCharSetName",
"SqlSortOrder",
"SqlSortOrderName",
"SuspendedDatabaseCount"
foreach ($propertyName in $properties) {
$query += " SELECT SERVERPROPERTY ('$propertyName') as value, cast('$propertyName' as varchar(100)) as PropertyName UNION `r`n"
}
$query = $query.Substring(0,$query.Length - 9)
Write-LogDebug "Serverproperty Query : $query" -DebugLogLevel 2
$result = execSQLQuery -SqlQuery $query
$emptyTBL = @{Empty=$true}
#if no connection, return null
if ($false -eq $result)
{
Write-LogDebug "Failed to connect to SQL instance (may be expected behavior)" -DebugLogLevel 2
return $emptyTBL
}
else
{
#We connected, but resultset is blank for some reason. Return null.
if ($result.Tables[0].rowcount -eq 0)
{
Write-LogDebug "No SERVERPROPERTY returned" -DebugLogLevel 2
return $emptyTBL
}
}
foreach ($row in $result.Tables[0].Rows) {
$SQLSERVERPROPERTYTBL.add($row.PropertyName.ToString().Trim(), $row.value)
}
$global:SQLSERVERPROPERTYTBL = $SQLSERVERPROPERTYTBL
return $SQLSERVERPROPERTYTBL
}
function getSQLConnection ([Boolean] $SkipStatusCheck = $false)
{
Write-LogDebug "inside " $MyInvocation.MyCommand
try
{
$globalCon = $global:SQLConnection
if ( $null -eq $globalCon)
{
Write-LogDebug "SQL Connection is null, initializing now" -DebugLogLevel 2
[System.Data.SqlClient.SqlConnection] $globalCon = New-Object System.Data.SqlClient.SqlConnection
$conString = getSQLConnectionString -SkipStatusCheck $SkipStatusCheck
if ($false -eq $conString )
{
#we failed to get proper conneciton string
Write-LogDebug "We failed to get connection string, check pervious messages to for more details" -DebugLogLevel 3
return $false
}
$globalCon.ConnectionString = $conString
$globalCon.Open() | Out-Null
$global:SQLConnection = $globalCon
} elseif (($globalCon.GetType() -eq [System.Data.SqlClient.SqlConnection]) -and ($globalCon.State -ne "Open") )
{
Write-LogDebug "Connection exists and is not Open, opening now" -DebugLogLevel 2
$globalCon.Open() | Out-Null
} elseif ( $globalCon.GetType() -ne [System.Data.SqlClient.SqlConnection])
{
Write-LogError "Could not create or obtain SqlConnection object " $globalCon.GetType()
return $false
}
return $globalCon
}
catch {
HandleCatchBlock -function_name $($MyInvocation.MyCommand) -err_rec $PSItem
return $false
}
}
function getSQLConnectionString ([Boolean] $SkipStatusCheck = $false)
{
Write-LogDebug "inside " $MyInvocation.MyCommand
try
{
if
(
($global:sql_instance_conn_str -eq $NO_INSTANCE_NAME) -or
($true -eq $global:instance_independent_collection ) -or
( ("Running" -ne $global:sql_instance_service_status) -and (-$false -eq $SkipStatusCheck) )
)
{
Write-LogWarning "No SQL Server instance found, instance is offline, or instance-independent collection. Not executing SQL queries."
return $false
}
elseif ([String]::IsNullOrEmpty($global:sql_instance_conn_str) -eq $false)
{
$SQLInstance = $global:sql_instance_conn_str
}
else
{
Write-LogError "SQL Server instance name is empty. Exiting..."
exit
}
Write-LogDebug "Received parameter SQLInstance: `"$SQLInstance`"" -DebugLogLevel 2
#default integrated security and encryption with trusted server certificate
return "Server=$SQLInstance;Database=master;Application Name=SQLLogScout;Integrated Security=True;Encrypt=True;TrustServerCertificate=true;"
}
catch {
HandleCatchBlock -function_name $($MyInvocation.MyCommand) -err_rec $PSItem
return $false
}
}
function getSQLCommand([Boolean] $SkipStatusCheck)
{
Write-LogDebug "inside " $MyInvocation.MyCommand
try
{
$SqlCmd = $global:SQLCommand
if ($null -eq $SqlCmd)
{
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$conn = getSQLConnection($SkipStatusCheck)
if ($false -eq $conn) {
#failed to obtain a connection
Write-LogDebug "Failed to get a connection object, check previous messages" -DebugLogLevel 3
return $false
}
$SqlCmd.Connection = $conn
}
if ($SqlCmd.GetType() -eq [System.Data.SqlClient.SqlCommand])
{
return $SqlCmd
}
Write-LogDebug "Did not get a valid SQLCommand , Type : $SqlCmd.GetType() " -DebugLogLevel 2
#if type is not correct don't return it
return $false
}
catch {
HandleCatchBlock -function_name $($MyInvocation.MyCommand) -err_rec $PSItem
return $false
}
}
function execSQLNonQuery ($SqlQuery,[Boolean] $TestFailure = $false)
{
Write-LogDebug "inside " $MyInvocation.MyCommand
return execSQLQuery -SqlQuery $SqlQuery -Command "ExecuteNonQuery" -TestFailure $TestFailure
}
function execSQLReader($SqlQuery, $CommandBehavior, $TestFailure = $false, $CommandType = [System.Data.CommandType]::StoredProcedure)
{
Write-LogDebug "inside " $MyInvocation.MyCommand
return execSQLQuery -SqlQuery $SqlQuery -Command "ExecuteReader" -CommandBehavior $CommandBehavior -TestFailure $TestFailure
}
function execSQLScalar ($SqlQuery, [int] $Timeout = 30, [Boolean] $TestFailure = $false)
{
Write-LogDebug "inside " $MyInvocation.MyCommand
return execSQLQuery -SqlQuery $SqlQuery -Command "ExecuteScalar" -Timeout $Timeout -TestFailure $TestFailure
}
function saveContentToFile()
{
[CmdletBinding()]
param
(
[Parameter(Mandatory, Position=0)]
[String]$content,
[Parameter(Mandatory, Position=1)]
[String] $fileName
)
Write-LogDebug "inside " $MyInvocation.MyCommand
$content | out-file $fileName | Out-Null
return $true
}
function saveSQLQuery()
{
[CmdletBinding()]
param
(
[Parameter(Mandatory, Position=0)]
[String]$SqlQuery,
[Parameter(Mandatory, Position=1)]
[String] $fileName,
[int] $Timeout = 30,
[Boolean] $TestFailure = $false
)
Write-LogDebug "inside " $MyInvocation.MyCommand
$DS = execSQLQuery -SqlQuery $SqlQuery -Timeout $Timeout -TestFailure $TestFailure
if ($DS.GetType() -eq [System.Data.DataSet])
{
try {
[String] $content =""
foreach ($row in $DS.Tables[0].Rows)
{
$content = $content + $row[0]
}
Write-LogDebug "Saving query to file $fileName"
$content | out-file $fileName | Out-Null
return $true
} catch
{
Write-LogError "Could not save query to file $fileName "
$mycommand = $MyInvocation.MyCommand
$error_msg = $PSItem.Exception.InnerException.Message
Write-LogError "$mycommand Function failed with error: $error_msg"
return $false
}
} else {
Write-LogDebug "Query failed, errors mabye in execSQLQuery messages " -DebugLogLevel 3
return $false
}
} #saveSQLQuery -SqlQuery -fileName
#execSQLQery connect to SQL Server using System.data objects
#The simplest way to use it is
<#
.SYNOPSIS
Returns false if query fails and Dataset if it succeeds
.DESCRIPTION
Returns false if query fails and Dataset if it succeeds
Can be used to perofrm ExecNonQuery and ExcuteReader as well
.EXAMPLE
execQuery -SqlQuery "SELECT 1 "
#>
function execSQLQuery()
{
[CmdletBinding()]
param
(
[Parameter(Mandatory, Position=0)]
[String]$SqlQuery,
[Parameter(Mandatory=$false)]
[Boolean]$SkipStatusCheck = $false,
[Parameter(Mandatory=$false)]
[Boolean]$TestFailure = $false,
[String]$Command = "SelectCommand",
[System.Data.CommandBehavior] $CommandBehavior,
[int] $Timeout = 30
)
Write-LogDebug "inside " $MyInvocation.MyCommand
#if in Teting Mode return false immediately
if ($TestFailure) { return $false }
$permittedCommands = "SelectCommand", "ExecuteNonQuery", "ExecuteReader", "ExecuteScalar"
if (-not( $permittedCommands -contains $command) )
{
Write-LogWarning "Permitted commands for execQuery are : " $permittedCommands.ToString
exit
}
Write-LogDebug "Creating SqlClient objects and setting parameters" -DebugLogLevel 2
$SqlCmd = getSQLCommand($SkipStatusCheck)
if ($false -eq $SqlCmd)
{
return $false
}
$SqlCmd.CommandText = $SqlQuery
$SqlCmd.CommandTimeout = $Timeout
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$DataSetResult = New-Object System.Data.DataSet
Write-LogDebug "About to call the required command : $Command " -DebugLogLevel 2
try {
if ($Command -eq "SelectCommand")
{
$SqlAdapter.SelectCommand = $SqlCmd
$SqlAdapter.Fill($DataSetResult) | Out-Null #fill method returns rowcount, Out-Null prevents the number from being printed in console
return $DataSetResult
} elseif ($Command -eq "ExecuteNonQuery")
{
$SqlCmd.ExecuteNonQuery() | Out-Null
return $true;
} elseif ($command -eq "ExecuteScalar") {
return $SqlCmd.ExecuteScalar()
} elseif ($Command -eq "ExecuteReader")
{
#this shold eventually be passed as parameter if other function will require different return values.
$SqlRetValue = New-Object System.Data.SqlClient.SqlParameter
$SqlRetValue.DbType = [System.Data.DbType]::Int32
$SqlRetValue.Direction = [System.Data.ParameterDirection]::ReturnValue
$SqlCmd.Parameters.Add($SqlRetValue) | Out-Null
#SQL Reader and ExecuteNonQuery can execute SP
$SqlCmd.CommandType = [System.Data.CommandType]::StoredProcedure
$SqlReader = $SqlCmd.ExecuteReader($CommandBehavior)
$result = [PSCustomObject] @{
SQLReader = $SqlReader
ReturnValue = $SqlRetValue
}
return $result;
}
}
catch
{
Write-LogError "Could not connect to SQL Server instance '$SQLInstance' to perform query."
$mycommand = $MyInvocation.MyCommand
$error_msg = $PSItem.Exception.InnerException.Message
Write-LogError "$mycommand Function failed with error: $error_msg"
# we can't connect to SQL, probably whole capture will fail, so we just abort here
return $false
}
}
function Start-SQLCmdProcess([string]$collector_name, [string]$input_script_name, [bool]$is_query=$false, [string]$query_text, [bool]$has_output_results=$true, [bool]$wait_sync=$false, [string]$server = $global:sql_instance_conn_str, [string]$setsqlcmddisplaywidth)
{
Write-LogDebug "Inside" $MyInvocation.MyCommand
[console]::TreatControlCAsInput = $true
if ($global:gDisableCtrlCasInput -eq "False")
{
[console]::TreatControlCAsInput = $true
}
# if query is empty and script should be populated
@ -516,7 +949,9 @@ function Start-SQLCmdProcess([string]$collector_name, [string]$input_script_name
$input_script = BuildInputScript $global:present_directory $input_script_name
$executable = "sqlcmd.exe"
$argument_list = "-S" + $server + " -E -Hsqllogscout -w8000"
#command arguments for sqlcmd; server connection, trusted connection, Hostname, wide output, and encryption negotiation
$argument_list = "-S" + $server + " -E -Hsqllogscout -w8000 -C -N"
#if secondary replica has read-intent, we add -KReadOnly to avoid failures on those secondaries
if ($global:is_secondary_read_intent_only -eq $true)
@ -524,6 +959,7 @@ function Start-SQLCmdProcess([string]$collector_name, [string]$input_script_name
$argument_list += " -KReadOnly"
}
#if query is passed, use the -Q parameter
if (($is_query -eq $true) -and ([string]::IsNullOrWhiteSpace($query_text) -ne $true) )
{
$argument_list += " -Q`"" + $query_text + "`""
@ -581,6 +1017,28 @@ function Start-SQLCmdProcess([string]$collector_name, [string]$input_script_name
#======================================== END of Process management section
#check if HADR is enabled from serverproperty
function isHADREnabled()
{
Write-LogDebug "Inside" $MyInvocation.MyCommand
$propertiesList = $global:SQLSERVERPROPERTYTBL
if (!$propertiesList) {
#We didn't receive server properteis
Write-LogError " getServerproperty returned no results "
return $false
}
$isHadrEnabled = $propertiesList."IsHadrEnabled"
if ($isHadrEnabled -eq "1") {
return $True
}
return $false
}
#check if cluster - based on cluster service status and cluster registry key
function IsClustered()
@ -845,3 +1303,238 @@ Function GetRegistryKeys
}
} #End of GetRegistryKeys
#Test connection functionality to see if SQL accessible.
function Test-SQLConnection ([string]$SQLServerName,[string]$SqlQuery)
{
Write-LogDebug "inside" $MyInvocation.MyCommand
if ([string]::IsNullOrEmpty($SqlQuery))
{
$Sqlquery = "SELECT @@SERVERNAME"
}
$DataSetPermissions = execSQLQuery -SqlQuery $Sqlquery -SkipStatusCheck $true #-TestFailure $true
if ($DataSetPermissions -eq $false) {
return $false;
} else {
return $true;
}
}
#Call this function to check if your version is supported checkSQLVersion -VersionsList @("SQL2022RTMCU8", "SQL2019RTMCU23")
#The function checks if current vesion is higher than versionsList, if you want it lowerthan, then user -LowerThan:$true
function checkSQLVersion ([String[]] $VersionsList, [Boolean]$LowerThan = $false, [Long] $SQLVersion = -1)
{
Write-LogDebug "inside" $MyInvocation.MyCommand
#in case we decide to pass the version , for testing or any other reason
if ($SQLVersion -eq -1) {
$currentSQLVersion = $global:SQLVERSION
} else {
$currentSQLVersion = $SQLVersion
}
[long[]] $versions = @()
foreach ($ver in $VersionsList)
{
$versions += $global:SqlServerVersionsTbl[$ver]
}
#upper limit is used to up the version to its ceiling
$upperLimit = 999999999
#count is needed to check if we are on the upper limit of the array
[int] $count = 0
$modulusFactor = 1000000000
#sorting is important to make sure we compare the upper limits first and exit early
if (-Not $LowerThan)
{
$sortedVersions = $versions | Sort-Object -Descending
} else {
$sortedVersions = $versions | Sort-Object
}
foreach ($v in $sortedVersions)
{
$vLower = $v - ($v % $modulusFactor)
#if we are on the head of the array, make the limit significantly high and low to encompass all above upper ad below lower.
if ($count -eq 0 )
{
$vUpper = $upperLimit * $modulusFactor * 1000
$vLower = 0
} else {
$vUpper = $vLower + $upperLimit
}
#This bit identifies the upper/lower limits to compare to, to avoid having copy of the same if statement
if (-Not $LowerThan) {
$gtBaseValue = $v
$leBaseValue = $vUpper
} else {
$gtBaseValue = $vLower
$leBaseValue = $v-1 #-1 needed to make sure we are less than Base not equl.
}
Write-LogDebug "current $currentSQLVersion gt $gtBaseValue lt $leBaseValue" -DebugLogLevel 3
if ($currentSQLVersion -ge $gtBaseValue -and $currentSQLVersion -le $leBaseValue )
{
Write-LogDebug "Version $currentSQLVersion is supported in $v" -DebugLogLevel 3
return $true
}
$count ++
}
Write-LogDebug "Version $currentSQLVersion is not supported" -DebugLogLevel 3
#we reach here, we are unsupported
return $false
}
function GetLogPathFromReg([string]$server, [string]$logType)
{
Write-LogDebug "Inside" $MyInvocation.MyCommand
try
{
$vInstance = ""
$vRegInst = ""
$RegPathParams = ""
$retLogPath = ""
$regInstNames = "HKLM:SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL"
# extract the instance name from the server name
$instByPort = GetSQLInstanceNameByPortNo($server)
Write-LogDebug "Result from GetSQLInstanceNameByPortNo is '$instByPort'" -DebugLogLevel 2
if ($true -ne [String]::IsNullOrWhiteSpace($instByPort))
{
$vInstance = $instByPort
}
else
{
if ($server -like '*\*')
{
$vInstance = Get-InstanceNameOnly($server)
}
else
{
$vInstance = "MSSQLSERVER"
}
}
Write-LogDebug "Instance name is $vInstance" -DebugLogLevel 2
# make sure a Instance Names is a valid registry key (could be missing if SQL Server is not installed or registry is corrupt)
if (Test-Path -Path $regInstNames)
{
$vRegInst = (Get-ItemProperty -Path $regInstNames).$vInstance
}
else
{
Write-LogDebug "Registry regInstNames='$regInstNames' is not valid or doesn't exist" -DebugLogLevel 2
return $false
}
# validate the registry value with the instance name appended to the end
# for example, HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL\SQL2017
if ([String]::IsNullOrWhiteSpace($vRegInst) -eq $true)
{
Write-LogDebug "Registry value vRegInst is null or empty. Not getting files from Log directory" -DebugLogLevel 2
return $false
}
else
{
# get the SQL Server registry key + instance name
$RegPathParams = "HKLM:SOFTWARE\Microsoft\Microsoft SQL Server\" + $vRegInst
switch ($logType)
{
{($_ -eq "ERRORLOG") -or ($_ -eq "POLYBASELOG")}
{
# go after the startup params registry key
$RegPathParams += "\MSSQLServer\Parameters"
# validate key to get the path to the ERRORLOG
if (Test-Path -Path $RegPathParams)
{
# strip the -e from the beginning of the string
$retLogPath = (Get-ItemProperty -Path $RegPathParams).SQLArg1 -replace "^-e", ""
# strip the word ERRORLOG from the end of the string
$retLogPath = Split-Path $retLogPath -Parent
if ($logType -eq "POLYBASELOG")
{
# append the PolyBase folder name to the end of the path
$retLogPath = $retLogPath + "\PolyBase\"
}
}
else
{
Write-LogDebug "Registry RegPathParams='$RegPathParams' is not valid or doesn't exist" -DebugLogLevel 2
return $false
}
}
"DUMPLOG"
{
# go after the dump configured registry key
# HKLM:SOFTWARE\Microsoft\Microsoft SQL Server\vRegInst\CPE
$vRegDmpPath = $RegPathParams + "\CPE"
if (Test-Path -Path $vRegDmpPath)
{
# strip the -e from the beginning of the string
$retLogPath = (Get-ItemProperty -Path $vRegDmpPath).ErrorDumpDir
}
else
{
Write-LogDebug "Registry RegDmpPath='$vRegDmpPath' is not valid or doesn't exist" -DebugLogLevel 2
return $false
}
}
Default
{
Write-LogDebug "Invalid logType='$logType' passed to GetLogPathFromReg()" -DebugLogLevel 2
return $false
}
}
}
# make sure the path to the log directory is valid
if (Test-Path -Path $retLogPath -PathType Container)
{
Write-LogDebug "Log path is $retLogPath" -DebugLogLevel 2
}
else
{
if ($logType -ne "POLYBASELOG")
{
Write-LogWarning "The directory $retLogPath is not accessible to collect logs. Check the disk is mounted and the folder is valid. Continuing with other collectors."
}
#Give user time to read the prompt.
Start-Sleep -Seconds 4
Write-LogDebug "Log path '$retLogPath' is not valid or doesn't exist" -DebugLogLevel 2
return $false
}
# return the path to directory pulled from registry
return $retLogPath
}
catch
{
HandleCatchBlock -function_name $($MyInvocation.MyCommand) -err_rec $PSItem
}
}
function setDisableCtrlCasInput
{
if ($global:gDisableCtrlCasInput -eq "False")
{
[console]::TreatControlCAsInput = $true
}
}

Просмотреть файл

@ -13,5 +13,7 @@
<Setup Value="0" />
<BackupRestore Value="0" />
<IO Value="0" />
<SsbDbMail Value="0" />
<NeverEndingQuery Value="0" />
</Scenario>
</root>

Просмотреть файл

@ -27,27 +27,28 @@ function Confirm-FileAttributes
[PSCustomObject]@{Algorithm = "SHA512"; Hash = "76DBE5D92A6ADBBAD8D7DCAAC5BD582DF5E87D6B7899882BB0D7489C557352219795106EBD3014BC76E07332FA899CE1B58B273AE5836B34653D4C545BBF89A4"; FileName = $pwdir + "\AlwaysOnDiagScript.sql"; FileSize = 21298}
,[PSCustomObject]@{Algorithm = "SHA512"; Hash = "4E2E0C0018B1AE4E6402D5D985B71E03E8AECBB9DA3145E63758343AEAC234E3D4988739CCE1AC034DDA7CE77482B27FB5C2A7A4E266E9C283F90593A1B562A2"; FileName = $pwdir + "\ChangeDataCapture.sql"; FileSize = 4672}
,[PSCustomObject]@{Algorithm = "SHA512"; Hash = "073C0BBAB692A88387AF355A0CEC7A069B7F6C442A8DABF4EFC46E54ACEC7B569B866778A66FE1ADEBF8AD4F30EF3EAF7EF32DD436BC023CD4BC3AD52923AB9F"; FileName = $pwdir + "\Change_Tracking.sql"; FileSize = 5110}
,[PSCustomObject]@{Algorithm = "SHA512"; Hash = "A5D2B75290F953A4F184EF700712C31580AC835ADD4D4A9D84C9D202FC04999E69933604C3BC8E05D2B3C4497675959B61BC2AD538518966516FE0AF52FFE5AD"; FileName = $pwdir + "\collecterrorlog.sql"; FileSize = 361}
,[PSCustomObject]@{Algorithm = "SHA512"; Hash = "2D349AE6F6AEFB934BB93451B99148137DB1A550831EF661945B361FE11F92E6FF73F540DCCBF87BB22AD386053042163227BEB43B9620F10BD966F55C6CD304"; FileName = $pwdir + "\HighCPU_perfstats.sql"; FileSize = 5360}
,[PSCustomObject]@{Algorithm = "SHA512"; Hash = "45833A77D15E7C6F2BF6849DC3469B637845D8465E431BFFBBEC78A90CEB7D3E2859FB83BD688EF75A895A232BAE01D97D10E6CB5DDB30453B311682EEDF534C"; FileName = $pwdir + "\High_IO_Perfstats.sql"; FileSize = 6435}
,[PSCustomObject]@{Algorithm = "SHA512"; Hash = "7E4BF16CD162F767D92AB5EE2FCBC0107DB43068A9EA45C68C2E1DD078C1FA15E9A10CEB63B9D8AEA237F4A2D96E7E5CE34AC30C2CEF304056D9FB287DF67971"; FileName = $pwdir + "\HighCPU_perfstats.sql"; FileSize = 6649}
,[PSCustomObject]@{Algorithm = "SHA512"; Hash = "D9FA1C31F90188779B00552755059A0E3747F768AA55DEBE702D039D7F942F7C4EA746EE7DE7AC02D0685DDFEED22854EB85B3268594D0A18F1147CA9C20D55A"; FileName = $pwdir + "\High_IO_Perfstats.sql"; FileSize = 9554}
,[PSCustomObject]@{Algorithm = "SHA512"; Hash = "824A41667D5DAA02729BB469E97701A41A09462EBBEDD2F5851061DC25465DC4422AD52DEDE1B5321FB55D485FDA6DBEE3B6429B303361078ACE3EF0581A8230"; FileName = $pwdir + "\linked_server_config.sql"; FileSize = 1184}
,[PSCustomObject]@{Algorithm = "SHA512"; Hash = "81FEFECB0F45598AE8A71511E025AD62439307CBA2FD7F71265C7B3E59008987BD0C2434906D43892CCDB7F38B49E9D0AA0842A24251D3FE4C6CFFB0C188E2BF"; FileName = $pwdir + "\MiscPssdiagInfo.sql"; FileSize = 17128}
,[PSCustomObject]@{Algorithm = "SHA512"; Hash = "B97914C0D8B53261A6C9CE93D6E306FE36A97FCE2F632C76FB180F2D1A2EC12510095CE35413D349386FD96B0F8EE54256EEE0AD9DA43CB0D386205D63F7EB20"; FileName = $pwdir + "\MiscDiagInfo.sql"; FileSize = 17791}
,[PSCustomObject]@{Algorithm = "SHA512"; Hash = "218F71ECDA1075B4D2B5785A94EF43569306BBDB026C163DFEAF33F960F802D13C65F1BC103CC2978F497A2EF5EA972EE89940C807188FC7366E11A1C30DB2D9"; FileName = $pwdir + "\MSDiagProcs.sql"; FileSize = 194123}
,[PSCustomObject]@{Algorithm = "SHA512"; Hash = "9789564CA007738B53D6CE21E6065A3D57D3E5A85DE85D32EC1456ED5A79CB1FA0265351FE402D266D6E90E31761DCED208AAA98EDA8BBC24AC25CF7819287D5"; FileName = $pwdir + "\Query Store.sql"; FileSize = 4870}
,[PSCustomObject]@{Algorithm = "SHA512"; Hash = "7216F9591ECB3C38BD962C146E57800687244B1C0E8450157E21CF5922BBBF92BB8431A814E0F5DF68933623DD76F9E4486A5D20162F58C232B8116920C252C7"; FileName = $pwdir + "\Profiler Traces.sql"; FileSize = 3601}
,[PSCustomObject]@{Algorithm = "SHA512"; Hash = "9789564CA007738B53D6CE21E6065A3D57D3E5A85DE85D32EC1456ED5A79CB1FA0265351FE402D266D6E90E31761DCED208AAA98EDA8BBC24AC25CF7819287D5"; FileName = $pwdir + "\QueryStore.sql"; FileSize = 4870}
,[PSCustomObject]@{Algorithm = "SHA512"; Hash = "7216F9591ECB3C38BD962C146E57800687244B1C0E8450157E21CF5922BBBF92BB8431A814E0F5DF68933623DD76F9E4486A5D20162F58C232B8116920C252C7"; FileName = $pwdir + "\ProfilerTraces.sql"; FileSize = 3601}
,[PSCustomObject]@{Algorithm = "SHA512"; Hash = "42BE545BC8D902A9D43146ACFC8D6A164242B567996C992D57CFBC6660B4E08051E7E687E2D140DAE5B17A8EEE652CFBD3904EC385702A2B8B666A980AE3C982"; FileName = $pwdir + "\Repl_Metadata_Collector.sql"; FileSize = 23414}
,[PSCustomObject]@{Algorithm = "SHA512"; Hash = "3659F226CD6CFD723D6137BDFA4570F7ACD35255E3DDA90653D57A26781D61CCD2FC1A984EDB774E2C377E44C230A412A9EEF93D8EC9CFA72DE2479D64153F92"; FileName = $pwdir + "\SQL Server Perf Stats Snapshot.sql"; FileSize = 34961}
,[PSCustomObject]@{Algorithm = "SHA512"; Hash = "325C084DEFC12C19224ABA31484EA42AC3144A13BA534F7163965837CE9D98B3D69B89C7D037F8CE72D7C073F34B83C55E2E6234BA590E58067EEDD5BE1CDA8D"; FileName = $pwdir + "\SQL Server Perf Stats.sql"; FileSize = 69524}
,[PSCustomObject]@{Algorithm = "SHA512"; Hash = "6159E67BD8E7EF981AFC72D574785548550A7D5CF9367697E6804E6731544F5930A5298D4D8446BAE254A5DB881E60394B884CF9D61BDD11266219A31FC42186"; FileName = $parentdir + "\SQL_LogScout.cmd"; FileSize = 2411}
,[PSCustomObject]@{Algorithm = "SHA512"; Hash = "D6448617265A9A7DAE8DA8F651642D507AEFEED211BBE0E9F9A4E4C542688129451F2E515BD8702A38D04E662D83DBC43098F4AA4EB58B014F451A66A23CC9E5"; FileName = $pwdir + "\SQL_Server_Mem_Stats.sql"; FileSize = 17163}
,[PSCustomObject]@{Algorithm = "SHA512"; Hash = "BE4C71610793F5912A8D90A7082B4B3A3581DD3AF3FD0C5FB6A08A129AB77B797E72CEFF0EA12486C3FEAA346ECA8394D18AB15B7FF74E1F9B13FA763ABD6278"; FileName = $pwdir + "\SSB_diag.sql"; FileSize = 11040}
,[PSCustomObject]@{Algorithm = "SHA512"; Hash = "A5AB03D93D7FB256C2DC08B9E5C46CF7D71C403F3074564A66E37DF46F75396BE69593DA2ECA2480073608C5FF215EDE36C6571155BD7EF6B2282C7888EF9401"; FileName = $pwdir + "\TempDB_and_Tran_Analysis.sql"; FileSize = 9054}
,[PSCustomObject]@{Algorithm = "SHA512"; Hash = "3089C42E8B2A1F4DE4EDD172C4D43F978147DB875D25989662C36286C755F46C462CF8AB1A163083B8BBB4973F97AC333752D5CFBDE2BBEFDDA1556CBC884485"; FileName = $pwdir + "\SQL_Server_PerfStats_Snapshot.sql"; FileSize = 36982}
,[PSCustomObject]@{Algorithm = "SHA512"; Hash = "275BF48FF8C495B6BA9217D2E5A3F7A7D1A7BDFF32AF035A2E9A03AF18773522816C6484B6F463C123B78572EF586CE846D9C1C36917E398A20E094D3836C58C"; FileName = $pwdir + "\SQL_Server_PerfStats.sql"; FileSize = 73276}
,[PSCustomObject]@{Algorithm = "SHA512"; Hash = "98DD9089860E83AD5116AFC88E8A58EF18F3BC99FE68AC4E37765AF3442D58D2DC3C6826E860C0F0604B2C4733F33396F0894C2ACA9E905346D7C4D5A4854185"; FileName = $parentdir + "\SQL_LogScout.cmd"; FileSize = 2564}
,[PSCustomObject]@{Algorithm = "SHA512"; Hash = "FC0FA00B999C9A6BF8CD55033A530C35D47F95CEE0156D540C77480E91180C7B9DBD303D5B73208D2C783D1FE628BF88AC845A4A452DD2FE3563E15E35A91BBD"; FileName = $pwdir + "\SQL_Server_Mem_Stats.sql"; FileSize = 35326}
,[PSCustomObject]@{Algorithm = "SHA512"; Hash = "96CD13704AD380D61BC763479C1509F5B6EFCC678558AE8EACE1869C4BCD1B80767115D109402E9FDF52C144CFD5D33AAFFF23FE6CFFDF62CD99590B37D5D6CF"; FileName = $pwdir + "\SSB_DbMail_Diag.sql"; FileSize = 12477}
,[PSCustomObject]@{Algorithm = "SHA512"; Hash = "2269D31F61959F08646C3E8B595191A110A8B559DEE43A60A5267B52A04F6A895E808CF2EC7C21B212BCAF9DD5AF3C25101B3C0FB91E8C1D6A2D1E42C9567FEC"; FileName = $pwdir + "\TempDB_and_Tran_Analysis.sql"; FileSize = 19749}
,[PSCustomObject]@{Algorithm = "SHA512"; Hash = "26FB26FBC977B8DD1D853CBE3ABD9FFAA87743CF7048F5E6549858422749B9BD8D6F2CA1AFE35C3A703407E252D8F3CDC887460D2400E69063E99E9E76D4AFFB"; FileName = $pwdir + "\xevent_AlwaysOn_Data_Movement.sql"; FileSize = 23164}
,[PSCustomObject]@{Algorithm = "SHA512"; Hash = "4EE3B0EE6CEA79CA9611489C2A351A7CCB27D3D5AD2691BE6380BF9C2D6270EE0CFC639B584A2307856384E7AA3B08462BCEA288D954786576DAFC4346670376"; FileName = $pwdir + "\xevent_backup_restore.sql"; FileSize = 1178}
,[PSCustomObject]@{Algorithm = "SHA512"; Hash = "DE42C1F05E42FF67BBE576EA8B8ADF443DD2D889CBE34F50F4320BE3DC793AF88F5DE13FDC46147CA69535691CC78ADB89463602F5364ED332F6F09A254B7948"; FileName = $pwdir + "\xevent_core.sql"; FileSize = 8134}
,[PSCustomObject]@{Algorithm = "SHA512"; Hash = "0BB73E8C889E80E8469E5F79F212399EBD50E13DAD39178B75E5578C5CD8E9EE3DCFE0B2D707423765DE8A215FEA9BBC389F30301071B41A5BD5AFCC1187A5DD"; FileName = $pwdir + "\xevent_detailed.sql"; FileSize = 27710}
,[PSCustomObject]@{Algorithm = "SHA512"; Hash = "C072CDC86FB9332246B2C7587D3DB2FB8755EA1BBBEE2F3A422FFDD672852CF832D6B2000F9F3FC81CEF46DC677DC0CE1D8AA8834DAF9B3A038228943E059F20"; FileName = $pwdir + "\xevent_general.sql"; FileSize = 23119})
,[PSCustomObject]@{Algorithm = "SHA512"; Hash = "9E09DC85282A3870A339B4928AE1E3D4ECE34B5346DA9E52BD18712A6E3D07241D80083C4A18206BBBA4D2971F13BC937CE6062C76FD83189D66B8704B0CBA1A"; FileName = $pwdir + "\xevent_detailed.sql"; FileSize = 25312}
,[PSCustomObject]@{Algorithm = "SHA512"; Hash = "2C5A3942093AC02FDE94626B327F6073056E4C14DA8AA13FE69404EFBABDF935B8622BA77316F630A2B313B7CE1EF20BC5A0A37E69FE38FFFCD794C16D82A71C"; FileName = $pwdir + "\xevent_general.sql"; FileSize = 20705}
,[PSCustomObject]@{Algorithm = "SHA512"; Hash = "F643167BBC7C3BAAA3A9916A5A83C951DEC49A11DF7335E231D778F02C5271C934A3EDBEE8DC01B7F0624B54C8AB37576289441C8A1867F02620F4B6328CCBAC"; FileName = $pwdir + "\xevent_servicebroker_dbmail.sql"; FileSize = 39706}
,[PSCustomObject]@{Algorithm = "SHA512"; Hash = "BF31CC80FDA7ED1DD52C88AE797B1FA186770DF005F3428D09785AD2307D6C059B71E5D8AF4EBF6A6AE60FF730519F25CEA934604BDD37CE8060BB38788CB497"; FileName = $pwdir + "\NeverEndingQuery_perfstats.sql"; FileSize = 6866}
)
# global array to keep a System.IO.FileStream object for each of the non-Powershell files
# files are opened with Read sharing before being hashed
# files are kept opened until SQL LogScout terminates preventing changes to them

Просмотреть файл

@ -5,13 +5,21 @@
[Collections.Generic.List[GenericModel]]$global:XeventsList_AlwaysOn = New-Object Collections.Generic.List[GenericModel]
[Collections.Generic.List[GenericModel]]$global:XeventsList_core = New-Object Collections.Generic.List[GenericModel]
[Collections.Generic.List[GenericModel]]$global:XeventsList_detailed = New-Object Collections.Generic.List[GenericModel]
[String[]]$global:varXevents = "xevent_AlwaysOn_Data_Movement", "xevent_core", "xevent_detailed" , "xevent_general"
[Collections.Generic.List[GenericModel]]$global:XeventsList_servicebroker_dbmail = New-Object Collections.Generic.List[GenericModel]
[Collections.Generic.List[ServiceState]]$global:List_service_name_status = New-Object Collections.Generic.List[ServiceState]
[String[]]$global:varXevents = "xevent_AlwaysOn_Data_Movement", "xevent_core", "xevent_detailed" , "xevent_general", "xevent_servicebroker_dbmail"
class GenericModel {
[String]$Caption
[String]$Value
[bool]$State
}
class ServiceState {
[String]$Name
[String]$Status
}
function InitializeGUIComponent() {
Write-LogDebug "inside" $MyInvocation.MyCommand
@ -50,6 +58,8 @@ function InitializeGUIComponent() {
$Global:SetupCheckBox = $Global:Window.FindName("SetupCheckBox")
$Global:BackupRestoreCheckBox = $Global:Window.FindName("BackupRestoreCheckBox")
$Global:IOCheckBox = $Global:Window.FindName("IOCheckBox")
$Global:ServiceBrokerDbMailCheckBox = $Global:Window.FindName("ServiceBrokerDbMailCheckBox")
$Global:NeverEndingQueryCheckBox = $Global:window.FindName("NeverEndingQueryCheckBox")
$Global:NoBasicCheckBox = $Global:Window.FindName("NoBasicCheckBox")
$Global:overrideExistingCheckBox = $Global:Window.FindName("overrideExistingCheckBox")
@ -61,26 +71,33 @@ function InitializeGUIComponent() {
$Global:list_xevent_detailed = $Global:Window.FindName("list_xevent_detailed")
$Global:list_xevent_core = $Global:Window.FindName("list_xevent_core")
$Global:list_xevent_AlwaysOn = $Global:Window.FindName("list_xevent_AlwaysOn")
$Global:list_xevent_servicebroker_dbmail = $Global:Window.FindName("list_xevent_servicebroker_dbmail")
$Global:TVI_xevent_general = $Global:Window.FindName("TVI_xevent_general")
$Global:TVI_xevent_detailed = $Global:Window.FindName("TVI_xevent_detailed")
$Global:TVI_xevent_core = $Global:Window.FindName("TVI_xevent_core")
$Global:TVI_xevent_AlwaysOn = $Global:Window.FindName("TVI_xevent_AlwaysOn")
$Global:TVI_xevent_servicebroker_dbmail = $Global:Window.FindName("TVI_xevent_servicebroker_dbmail")
$Global:xeventcore_CheckBox = $Global:Window.FindName("xeventcore_CheckBox")
$Global:XeventAlwaysOn_CheckBox = $Global:Window.FindName("XeventAlwaysOn_CheckBox")
$Global:XeventGeneral_CheckBox = $Global:Window.FindName("XeventGeneral_CheckBox")
$Global:XeventDetailed_CheckBox = $Global:Window.FindName("XeventDetailed_CheckBox")
$Global:XeventServiceBrokerDbMail_CheckBox = $Global:Window.FindName("XeventServiceBrokerDbMail_CheckBox")
#set the output folder to be parent of folder where execution files reside
$Global:txtPresentDirectory.Text = (Get-Item $CurrentDirectory).Parent.FullName
#Read current config.
$Global:XmlDataProviderName.Source = $ConfigPath
#Setting the item source for verious lists.
#Setting the item source for various lists.
$Global:listExtraSkills.ItemsSource = $Global:list
$Global:listXevnets.ItemsSource = $Global:XeventsList_general
$Global:list_xevent_detailed.ItemsSource = $Global:XeventsList_detailed
$Global:list_xevent_core.ItemsSource = $Global:XeventsList_core
$Global:list_xevent_AlwaysOn.ItemsSource = $Global:XeventsList_AlwaysOn
$Global:list_xevent_servicebroker_dbmail.ItemsSource = $Global:XeventsList_servicebroker_dbmail
RegisterEvents
Set-PresentDirectory
@ -116,28 +133,40 @@ function RegisterEvents() {
$Global:generalPerfCheckBox.Add_Click({ generalPerfCheckBox_Click_EventHandler $Global:generalPerfCheckBox.IsChecked })
$Global:LightPerfCheckBox.Add_Click({ LightPerfCheckBox_Click_EventHandler $Global:LightPerfCheckBox.IsChecked })
$Global:alwaysOnPerfCheckBox.Add_Click({ alwaysOnPerfCheckBox_Click_EventHandler $Global:alwaysOnPerfCheckBox.IsChecked })
$Global:ServiceBrokerDbMailCheckBox.Add_Click({ ServiceBrokerDbMailCheckBox_Click_EventHandler $Global:ServiceBrokerDbMailCheckBox.IsChecked })
#perfmon counters
$Global:memoryCheckBox.Add_Click({ Manage_PerfmonCounters $Global:memoryCheckBox.IsChecked })
$Global:BackupRestoreCheckBox.Add_Click({ Manage_PerfmonCounters $Global:BackupRestoreCheckBox.IsChecked })
$Global:IOCheckBox.Add_Click({ Manage_PerfmonCounters $Global:IOCheckBox.IsChecked })
$Global:basicPerfCheckBox.Add_Click({ Manage_PerfmonCounters $Global:basicPerfCheckBox.IsChecked })
$Global:NoBasicCheckBox.Add_Click({ Manage_PerfmonCounters $Global:NoBasicCheckBox.IsChecked })
#xevents
$Global:xeventcore_CheckBox.Add_Click({ HandleCeventcore_CheckBoxClick $Global:xeventcore_CheckBox.IsChecked })
$Global:XeventAlwaysOn_CheckBox.Add_Click({ AlwaysOn_CheckBoxClick $Global:XeventAlwaysOn_CheckBox.IsChecked })
$Global:XeventGeneral_CheckBox.Add_Click({ XeventGeneral_CheckBoxClick $Global:XeventGeneral_CheckBox.IsChecked })
$Global:XeventDetailed_CheckBox.Add_Click({ XeventDetailed_CheckBoxClick $Global:XeventDetailed_CheckBox.IsChecked })
$Global:NeverEndingQueryCheckBox.Add_Click({ Manage_PerfmonCounters $Global:NeverEndingQueryCheckBox.IsChecked })
}
function HandleCeventcore_CheckBoxClick([bool] $state) {
foreach ($item in $Global:XeventsList_core) {
$item.State = $state
[GenericModel] $item = $item
if ($item.Caption -like "*existing_connection*" ) {
#This should remain always seleted because core xevents is needed to create the main event
$item.State = $true
} else {
$item.State = $state
}
}
$Global:list_xevent_core.ItemsSource = $null
$Global:list_xevent_core.ItemsSource = $Global:XeventsList_core
$Global:xeventcore_CheckBox.IsChecked = $state
#Core xevent collection is needed because it is the one that creates xevent_SQLLogScout session
$Global:xeventcore_CheckBox.IsChecked = $Global:TVI_xevent_core.IsEnabled #$state
}
function AlwaysOn_CheckBoxClick([bool] $state) {
@ -176,6 +205,18 @@ function XeventDetailed_CheckBoxClick([bool] $state) {
}
function XeventServiceBrokerDbMail_CheckBoxClick([bool] $state) {
foreach ($item in $Global:XeventsList_servicebroker_dbmail) {
$item.State = $state
}
$Global:XeventServiceBrokerDbMail_CheckBox.IsChecked = $state
$Global:list_xevent_servicebroker_dbmail.ItemsSource = $null
$Global:list_xevent_servicebroker_dbmail.ItemsSource = $Global:XeventsList_servicebroker_dbmail
}
function ButtonPresentDirectory_EventHandler() {
$objForm = New-Object System.Windows.Forms.FolderBrowserDialog
$Show = $objForm.ShowDialog()
@ -185,19 +226,23 @@ function ButtonPresentDirectory_EventHandler() {
}
function Window_Loaded_EventHandler() {
Foreach ($Instance in Get-NetNameMatchingInstance) { $ComboBoxInstanceName.Items.Add($Instance) }
BuildServiceNameStatusModel
BuildPermonModel
BuildXEventsModel
BuildXEventsModel_core
BuildXEventsModel_detailed
BuildXEventsModel_AlwaysOn
BuildXEventsModel_servicebroker_dbmail
Manage_PerfmonCounters($false)
HandleCeventcore_CheckBoxClick($false)
AlwaysOn_CheckBoxClick($false)
XeventGeneral_CheckBoxClick($false)
XeventDetailed_CheckBoxClick($false)
# $Global:listExtraSkills = $Global:Window.FindName("listExtraSkills")
# listExtraSkills
XeventServiceBrokerDbMail_CheckBoxClick($false)
}
function Manage_PerfmonCounters([bool] $state) {
if ($Global:DetailedPerfCheckBox.IsChecked -or
@ -207,6 +252,9 @@ function Manage_PerfmonCounters([bool] $state) {
$Global:memoryCheckBox.IsChecked -or
$Global:BackupRestoreCheckBox.IsChecked -or
$Global:IOCheckBox.IsChecked -or
$Global:basicPerfCheckBox.IsChecked -or
$Global:NeverEndingQueryCheckBox.IsChecked -or
$Global:ServiceBrokerDbMailCheckBox.IsChecked -or
$Global:basicPerfCheckBox.IsChecked) {
$Global:listExtraSkills.IsEnabled = $true
foreach ($item in $Global:list) {
@ -288,6 +336,18 @@ function alwaysOnPerfCheckBox_Click_EventHandler([bool] $state) {
}
}
function ServiceBrokerDbMailCheckBox_Click_EventHandler([bool] $state) {
$Global:TVI_xevent_core.IsEnabled = $state
$Global:TVI_xevent_servicebroker_dbmail.IsEnabled = $state
XeventServiceBrokerDbMail_CheckBoxClick($state)
HandleCeventcore_CheckBoxClick($state)
Manage_PerfmonCounters($state)
}
function Set-Mode() {
try {
@ -370,6 +430,12 @@ function EnableScenarioFromGUI {
if ($Global:IOCheckBox.IsChecked) {
$global:gScenario += "IO+"
}
if ($Global:NeverEndingQueryCheckBox.IsChecked) {
$global:gScenario += "NeverEndingQuery+"
}
if ($Global:ServiceBrokerDbMailCheckBox.IsChecked) {
$global:gScenario += "ServiceBrokerDbMail+"
}
if ($Global:NoBasicCheckBox.IsChecked) {
$global:gScenario += "NoBasic+"
}
@ -399,60 +465,45 @@ function DisableAll([bool] $state) {
# $Global:basicPerfCheckBox.IsEnabled = !$state
$Global:generalPerfCheckBox.IsChecked = $false
$Global:DetailedPerfCheckBox.IsChecked = $false
$Global:LightPerfCheckBox.IsChecked = $false
$Global:replicationPerfCheckBox.IsChecked = $false
$Global:alwaysOnPerfCheckBox.IsChecked = $false
$Global:networkTraceCheckBox.IsChecked = $false
$Global:memoryCheckBox.IsChecked = $false
$Global:dumpMemoryCheckBox.IsChecked = $false
$Global:SetupCheckBox.IsChecked = $false
$Global:BackupRestoreCheckBox.IsChecked = $false
$Global:IOCheckBox.IsChecked = $false
$Global:NeverEndingQueryCheckBox.IsChecked = $false
$Global:ServiceBrokerDbMailCheckBox.IsChecked = $false
$Global:generalPerfCheckBox.IsEnabled = !$state
$Global:DetailedPerfCheckBox.IsEnabled = !$state
$Global:LightPerfCheckBox.IsEnabled = !$state
$Global:replicationPerfCheckBox.IsEnabled = !$state
$Global:alwaysOnPerfCheckBox.IsEnabled = !$state
$Global:networkTraceCheckBox.IsEnabled = !$state
$Global:memoryCheckBox.IsEnabled = !$state
$Global:dumpMemoryCheckBox.IsEnabled = !$state
$Global:SetupCheckBox.IsEnabled = !$state
$Global:BackupRestoreCheckBox.IsEnabled = !$state
$Global:IOCheckBox.IsEnabled = !$state
$Global:NeverEndingQueryCheckBox.IsEnabled = !$state
$Global:ServiceBrokerDbMailCheckBox.IsEnabled = !$state
}
function GenerateXeventFileFromGUI {
Write-LogDebug "inside" $MyInvocation.MyCommand
try {
CreateFile $Global:XeventsList_general "xevent_general.sql"
MakeSureCreateBeforeAlterEvent $Global:XeventsList_core "EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT"
CreateFile $Global:XeventsList_core 'xevent_core.sql'
CreateFile $Global:XeventsList_detailed 'xevent_detailed.sql'
CreateFile -mylist $Global:XeventsList_general -fileName "xevent_general.sql"
MakeSureCreateBeforeAlterEvent -mylist $Global:XeventsList_core -pattern "EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT"
CreateFile -mylist $Global:XeventsList_core -fileName 'xevent_core.sql'
CreateFile -mylist $Global:XeventsList_detailed -fileName 'xevent_detailed.sql'
MakeSureCreateBeforeAlterEvent $Global:XeventsList_AlwaysOn " EVENT SESSION [SQLLogScout_AlwaysOn_Data_Movement] ON SERVER"
CreateFile $Global:XeventsList_AlwaysOn 'xevent_AlwaysOn_Data_Movement.sql'
CreateFile -mylist $Global:XeventsList_servicebroker_dbmail -fileName 'xevent_servicebroker_dbmail.sql'
MakeSureCreateBeforeAlterEvent -mylist $Global:XeventsList_AlwaysOn -pattern " EVENT SESSION [SQLLogScout_AlwaysOn_Data_Movement] ON SERVER"
CreateFile -mylist $Global:XeventsList_AlwaysOn -fileName 'xevent_AlwaysOn_Data_Movement.sql'
}
catch {
HandleCatchBlock -function_name $($MyInvocation.MyCommand) -err_rec $PSItem
@ -637,4 +688,64 @@ function BuildXEventsModel_AlwaysOn() {
exit
}
}
}
function BuildXEventsModel_servicebroker_dbmail() {
try {
Write-LogDebug "inside" $MyInvocation.MyCommand
$xevent_string = New-Object -TypeName System.Text.StringBuilder
$GenericModelobj = New-Object GenericModel
foreach ($element in Get-Content .\xevent_servicebroker_dbmail.sql) {
if ($element -eq "GO") {
$GenericModelobj.Value = $xevent_string
$GenericModelobj.State = $true
$global:XeventsList_servicebroker_dbmail.Add($GenericModelobj)
# reset the object and string builder
$GenericModelobj = New-Object GenericModel
$xevent_string = New-Object -TypeName System.Text.StringBuilder
[void]$xevent_string.Append("GO `r`n")
}
else {
[void]$xevent_string.Append($element)
[void]$xevent_string.Append("`r`n")
#$GenericModelobj.Value = $line
# get the event name from the event session and add it to the model
if ($element.contains("[xevent_SQLLogScout]")) {
$temp = $element.split('(')[0].split('.')
if ($temp.count -eq 2) {
$GenericModelobj.Caption = $temp[1]
}
}
}
}
}
catch {
HandleCatchBlock -function_name $($MyInvocation.MyCommand) -err_rec $PSItem
exit
}
}
function BuildServiceNameStatusModel() {
try
{
foreach ($Instance in Get-NetNameMatchingInstance)
{
$global:List_service_name_status.Add((New-Object ServiceState -Property @{Name=$Instance.Name; Status=$Instance.Status}))
}
$ComboBoxInstanceName.ItemsSource = $global:List_service_name_status
}
catch
{
HandleCatchBlock -function_name $($MyInvocation.MyCommand) -err_rec $PSItem
exit
}
}

Просмотреть файл

@ -11,77 +11,74 @@ SET QUOTED_IDENTIFIER ON
SET NUMERIC_ROUNDABORT OFF
GO
IF OBJECT_ID ('#sp_perf_high_cpu_snapshots','P') IS NOT NULL
DROP PROCEDURE #sp_perf_high_cpu_snapshots
GO
CREATE PROCEDURE #sp_perf_high_cpu_snapshots @appname sysname='sqllogscout', @runtime datetime, @runtime_utc datetime
as
set nocount on
AS
SET NOCOUNT ON
BEGIN
DECLARE @msg varchar(100)
BEGIN TRY
DECLARE @msg varchar(100)
IF NOT EXISTS (SELECT * FROM sys.dm_exec_requests req left outer join sys.dm_exec_sessions sess
on req.session_id = sess.session_id
WHERE req.session_id <> @@SPID AND ISNULL (sess.host_name, '') != @appname and is_user_process = 1)
BEGIN
PRINT 'No active queries'
END
ELSE
BEGIN
-- select ''
IF @runtime IS NULL or @runtime_utc IS NULL
BEGIN
SET @runtime = GETDATE()
SET @runtime_utc = GETUTCDATE()
SET @msg = 'Start time: ' + CONVERT (varchar(30), @runtime, 126)
RAISERROR (@msg, 0, 1) WITH NOWAIT
END
IF NOT EXISTS (SELECT * FROM sys.dm_exec_requests req left outer join sys.dm_exec_sessions sess
on req.session_id = sess.session_id
WHERE req.session_id <> @@SPID AND ISNULL (sess.host_name, '') != @appname and is_user_process = 1)
BEGIN
PRINT 'No active queries'
END
ELSE
BEGIN
-- select ''
IF @runtime IS NULL or @runtime_utc IS NULL
BEGIN
SET @runtime = GETDATE()
SET @runtime_utc = GETUTCDATE()
SET @msg = 'Start time: ' + CONVERT (varchar(30), @runtime, 126)
RAISERROR (@msg, 0, 1) WITH NOWAIT
END
print ''
RAISERROR ('-- high_cpu_queries --', 0, 1) WITH NOWAIT
select CONVERT (varchar(30), @runtime, 126) as runtime, CONVERT (varchar(30), @runtime_utc, 126) as runtime_utc, req.session_id, thrd.os_thread_id, req.start_time as request_start_time, req.cpu_time, req.total_elapsed_time, req.logical_reads,
req.status, req.command, req.wait_type, req.wait_time, req.scheduler_id, req.granted_query_memory, tsk.task_state, tsk.context_switches_count,
replace(replace(substring(ISNULL(SQLText.text, ''),1,1000),CHAR(10), ' '),CHAR(13), ' ') as batch_text,
ISNULL(sess.program_name, '') as program_name, ISNULL (sess.host_name, '') as Host_name, ISNULL(sess.host_process_id,0) as session_process_id,
ISNULL (conn.net_packet_size, 0) AS 'net_packet_size', LEFT (ISNULL (conn.client_net_address, ''), 20) AS 'client_net_address',
substring
(REPLACE
(REPLACE
(SUBSTRING
(SQLText.text
, (req.statement_start_offset/2) + 1
, (
(CASE statement_END_offset
WHEN -1
THEN DATALENGTH(SQLText.text)
ELSE req.statement_END_offset
END
- req.statement_start_offset)/2) + 1)
, CHAR(10), ' '), CHAR(13), ' '), 1, 512) AS active_statement_text
from sys.dm_exec_requests req
LEFT OUTER JOIN sys.dm_exec_connections conn on conn.session_id = req.session_id
OUTER APPLY sys.dm_exec_sql_text (ISNULL (req.sql_handle, conn.most_recent_sql_handle)) as SQLText
left outer join sys.dm_exec_sessions sess on conn.session_id = sess.session_id
left outer join sys.dm_os_tasks tsk on sess.session_id = tsk.session_id --including this to get task state (SPINLOOCK state is crucial)
inner join sys.dm_os_threads thrd ON tsk.worker_address = thrd.worker_address
where sess.is_user_process = 1
and req.cpu_time > 60000
--this is to prevent massive grants
option (max_grant_percent = 3, MAXDOP 1)
--flush results to client
RAISERROR (' ', 0, 1) WITH NOWAIT
END
print ''
RAISERROR ('-- high_cpu_queries --', 0, 1) WITH NOWAIT
select CONVERT (varchar(30), @runtime, 126) as runtime, CONVERT (varchar(30), @runtime_utc, 126) as runtime_utc, req.session_id, thrd.os_thread_id, req.start_time as request_start_time, req.cpu_time, req.total_elapsed_time, req.logical_reads,
req.status, req.command, req.wait_type, req.wait_time, req.scheduler_id, req.granted_query_memory, tsk.task_state, tsk.context_switches_count,
replace(replace(substring(ISNULL(SQLText.text, ''),1,1000),CHAR(10), ' '),CHAR(13), ' ') as batch_text,
ISNULL(sess.program_name, '') as program_name, ISNULL (sess.host_name, '') as Host_name, ISNULL(sess.host_process_id,0) as session_process_id,
ISNULL (conn.net_packet_size, 0) AS 'net_packet_size', LEFT (ISNULL (conn.client_net_address, ''), 20) AS 'client_net_address',
substring
(REPLACE
(REPLACE
(SUBSTRING
(SQLText.text
, (req.statement_start_offset/2) + 1
, (
(CASE statement_END_offset
WHEN -1
THEN DATALENGTH(SQLText.text)
ELSE req.statement_END_offset
END
- req.statement_start_offset)/2) + 1)
, CHAR(10), ' '), CHAR(13), ' '), 1, 512) AS active_statement_text
from sys.dm_exec_requests req
LEFT OUTER JOIN sys.dm_exec_connections conn on conn.session_id = req.session_id
OUTER APPLY sys.dm_exec_sql_text (ISNULL (req.sql_handle, conn.most_recent_sql_handle)) as SQLText
left outer join sys.dm_exec_sessions sess on conn.session_id = sess.session_id
left outer join sys.dm_os_tasks tsk on sess.session_id = tsk.session_id --including this to get task state (SPINLOOCK state is crucial)
inner join sys.dm_os_threads thrd ON tsk.worker_address = thrd.worker_address
where sess.is_user_process = 1
and req.cpu_time > 60000
--this is to prevent massive grants
option (max_grant_percent = 3, MAXDOP 1)
--flush results to client
RAISERROR (' ', 0, 1) WITH NOWAIT
END
END TRY
BEGIN CATCH
PRINT 'Exception occured in: "' + OBJECT_NAME(@@PROCID) + '"'
PRINT 'Msg ' + isnull(cast(Error_Number() as nvarchar(50)), '') + ', Level ' + isnull(cast(Error_Severity() as nvarchar(50)),'') + ', State ' + isnull(cast(Error_State() as nvarchar(50)),'') + ', Server ' + @@servername + ', Line ' + isnull(cast(Error_Line() as nvarchar(50)),'') + char(10) + Error_Message() + char(10);
END CATCH
END
GO
@ -89,65 +86,63 @@ if object_id ('#sp_run_highcpu_perfstats','p') is not null
drop procedure #sp_Run_HighCPU_PerfStats
go
create procedure #sp_Run_HighCPU_PerfStats
as
AS
BEGIN TRY
-- Main loop
print 'starting high cpu perf stats script...'
set language us_english
print '-- script source --'
select 'high cpu perf stats script' as script_name, '$revision: 16 $ ($change: ? $)' as revision
print ''
print '-- script and environment details --'
print 'name value'
print '------------------------ ---------------------------------------------------'
print 'sql server name ' + @@servername
print 'machine name ' + convert (varchar, serverproperty ('machinename'))
print 'sql version (sp) ' + convert (varchar, serverproperty ('productversion')) + ' (' + convert (varchar, serverproperty ('productlevel')) + ')'
print 'edition ' + convert (varchar, serverproperty ('edition'))
print 'script name sql server perf stats script'
print 'script file name $file: highcpu_perfstats.sql $'
print 'revision $revision: 16 $ ($change: ? $)'
print 'last modified $date: 2019/11/16 $'
print 'script begin time ' + convert (varchar(30), getdate(), 126)
print 'current database ' + db_name()
print '@@spid ' + ltrim(str(@@spid))
print ''
print 'starting high cpu perf stats script...'
set language us_english
print '-- script source --'
select 'high cpu perf stats script' as script_name, '$revision: 16 $ ($change: ? $)' as revision
print ''
print '-- script and environment details --'
print 'name value'
print '------------------------ ---------------------------------------------------'
print 'sql server name ' + @@servername
print 'machine name ' + convert (varchar, serverproperty ('machinename'))
print 'sql version (sp) ' + convert (varchar, serverproperty ('productversion')) + ' (' + convert (varchar, serverproperty ('productlevel')) + ')'
print 'edition ' + convert (varchar, serverproperty ('edition'))
print 'script name sql server perf stats script'
print 'script file name $file: highcpu_perfstats.sql $'
print 'revision $revision: 16 $ ($change: ? $)'
print 'last modified $date: 2019/11/16 $'
print 'script begin time ' + convert (varchar(30), getdate(), 126)
print 'current database ' + db_name()
print '@@spid ' + ltrim(str(@@spid))
print ''
DECLARE @runtime datetime, @runtime_utc datetime, @prevruntime datetime
DECLARE @msg varchar(100)
SELECT @prevruntime = sqlserver_start_time from sys.dm_os_sys_info
--set prevtime to 5 min earlier, in case SQL just started
SET @prevruntime = DATEADD(SECOND, -300, @prevruntime)
DECLARE @runtime datetime, @runtime_utc datetime, @prevruntime datetime
DECLARE @msg varchar(100)
WHILE (1=1)
BEGIN
BEGIN TRY
SET @runtime = GETDATE()
SET @runtime_utc = GETUTCDATE()
SET @msg = 'Start time: ' + CONVERT (varchar(30), @runtime, 126)
SELECT @prevruntime = sqlserver_start_time from sys.dm_os_sys_info
--set prevtime to 5 min earlier, in case SQL just started
SET @prevruntime = DATEADD(SECOND, -300, @prevruntime)
WHILE (1=1)
BEGIN
SET @runtime = GETDATE()
SET @runtime_utc = GETUTCDATE()
SET @msg = 'Start time: ' + CONVERT (varchar(30), @runtime, 126)
PRINT ''
RAISERROR (@msg, 0, 1) WITH NOWAIT
-- Collect sp_perf_high_Cpu_snapshot every 3 minutes
exec #sp_perf_high_cpu_snapshots 'sqllogscout', @runtime = @runtime, @runtime_utc = @runtime_utc
SET @prevruntime = @runtime
WAITFOR DELAY '0:00:30'
END
PRINT ''
RAISERROR (@msg, 0, 1) WITH NOWAIT
-- Collect sp_perf_high_Cpu_snapshot every 3 minutes
exec #sp_perf_high_cpu_snapshots 'sqllogscout', @runtime = @runtime, @runtime_utc = @runtime_utc
SET @prevruntime = @runtime
WAITFOR DELAY '0:00:30'
END TRY
BEGIN CATCH
PRINT 'Exception occured in: "' + OBJECT_NAME(@@PROCID) + '"'
PRINT 'Msg ' + isnull(cast(Error_Number() as nvarchar(50)), '') + ', Level ' + isnull(cast(Error_Severity() as nvarchar(50)),'') + ', State ' + isnull(cast(Error_State() as nvarchar(50)),'') + ', Server ' + @@servername + ', Line ' + isnull(cast(Error_Line() as nvarchar(50)),'') + char(10) + Error_Message() + char(10);
END CATCH
END
END TRY
BEGIN CATCH
PRINT 'Exception occured in: "' + OBJECT_NAME(@@PROCID) + '"'
PRINT 'Msg ' + isnull(cast(Error_Number() as nvarchar(50)), '') + ', Level ' + isnull(cast(Error_Severity() as nvarchar(50)),'') + ', State ' + isnull(cast(Error_State() as nvarchar(50)),'') + ', Server ' + @@servername + ', Line ' + isnull(cast(Error_Line() as nvarchar(50)),'') + char(10) + Error_Message() + char(10);
END CATCH
GO
exec #sp_Run_HighCPU_PerfStats

Просмотреть файл

@ -15,98 +15,135 @@ IF OBJECT_ID ('#sp_perf_virtual_file_stats','P') IS NOT NULL
DROP PROCEDURE #sp_perf_virtual_file_stats
GO
CREATE PROCEDURE #sp_perf_virtual_file_stats @appname sysname='sqllogscout', @runtime datetime, @runtime_utc datetime
as
set nocount on
AS
SET NOCOUNT ON
BEGIN
print ''
print '-- file_io_stats --'
SELECT CONVERT (varchar(30), @runtime, 126) as runtime, CONVERT (varchar(30), @runtime_utc, 126) as runtime_utc,
CONVERT(VARCHAR(40), DB_NAME(vfs.database_id)) AS database_name, physical_name AS Physical_Name,
size_on_disk_bytes / 1024 / 1024.0 AS File_Size_MB ,
CAST(io_stall_read_ms/(1.0 + num_of_reads) AS NUMERIC(10,1)) AS Average_Read_Latency,
CAST(io_stall_write_ms/(1.0 + num_of_writes) AS NUMERIC(10,1)) AS Average_Write_Latency,
num_of_bytes_read / NULLIF(num_of_reads, 0) AS Average_Bytes_Read,
num_of_bytes_written / NULLIF(num_of_writes, 0) AS Average_Bytes_Write
FROM sys.dm_io_virtual_file_stats(NULL, NULL) AS vfs
JOIN sys.master_files AS mf
ON vfs.database_id = mf.database_id AND vfs.file_id = mf.file_id
WHERE (CAST(io_stall_write_ms/(1.0 + num_of_writes) AS NUMERIC(10,1))> 15
OR (CAST(io_stall_read_ms/(1.0 + num_of_reads) AS NUMERIC(10,1))> 15))
ORDER BY Average_Read_Latency DESC
OPTION (max_grant_percent = 3, MAXDOP 1)
BEGIN TRY
print ''
print '-- file_io_stats --'
SELECT CONVERT (varchar(30), @runtime, 126) as runtime, CONVERT (varchar(30), @runtime_utc, 126) as runtime_utc,
CONVERT(VARCHAR(40), DB_NAME(vfs.database_id)) AS database_name, physical_name AS Physical_Name,
size_on_disk_bytes / 1024 / 1024.0 AS File_Size_MB ,
CAST(io_stall_read_ms/(1.0 + num_of_reads) AS NUMERIC(10,1)) AS Average_Read_Latency,
CAST(io_stall_write_ms/(1.0 + num_of_writes) AS NUMERIC(10,1)) AS Average_Write_Latency,
num_of_bytes_read / NULLIF(num_of_reads, 0) AS Average_Bytes_Read,
num_of_bytes_written / NULLIF(num_of_writes, 0) AS Average_Bytes_Write
FROM sys.dm_io_virtual_file_stats(NULL, NULL) AS vfs
JOIN sys.master_files AS mf
ON vfs.database_id = mf.database_id AND vfs.file_id = mf.file_id
WHERE (CAST(io_stall_write_ms/(1.0 + num_of_writes) AS NUMERIC(10,1))> 15
OR (CAST(io_stall_read_ms/(1.0 + num_of_reads) AS NUMERIC(10,1))> 15))
ORDER BY Average_Read_Latency DESC
OPTION (max_grant_percent = 3, MAXDOP 1)
--flush results to client
RAISERROR (' ', 0, 1) WITH NOWAIT
--flush results to client
RAISERROR (' ', 0, 1) WITH NOWAIT
END TRY
BEGIN CATCH
PRINT 'Exception occured in: "' + OBJECT_NAME(@@PROCID) + '"'
PRINT 'Msg ' + isnull(cast(Error_Number() as nvarchar(50)), '') + ', Level ' + isnull(cast(Error_Severity() as nvarchar(50)),'') + ', State ' + isnull(cast(Error_State() as nvarchar(50)),'') + ', Server ' + @@servername + ', Line ' + isnull(cast(Error_Line() as nvarchar(50)),'') + char(10) + Error_Message() + char(10);
END CATCH
END
GO
IF OBJECT_ID ('#sp_perf_io_snapshots','P') IS NOT NULL
DROP PROCEDURE #sp_perf_io_snapshots
GO
CREATE PROCEDURE #sp_perf_io_snapshots @appname sysname='sqllogscout', @runtime datetime, @runtime_utc datetime
as
set nocount on
AS
SET NOCOUNT ON
BEGIN
DECLARE @msg varchar(100)
BEGIN TRY
IF NOT EXISTS (SELECT * FROM sys.dm_exec_requests req left outer join sys.dm_exec_sessions sess
on req.session_id = sess.session_id
WHERE req.session_id <> @@SPID AND ISNULL (sess.host_name, '') != @appname and is_user_process = 1)
BEGIN
PRINT 'No active queries'
END
ELSE
BEGIN
DECLARE @msg varchar(100)
IF NOT EXISTS (SELECT * FROM sys.dm_exec_requests req left outer join sys.dm_exec_sessions sess
on req.session_id = sess.session_id
WHERE req.session_id <> @@SPID AND ISNULL (sess.host_name, '') != @appname and is_user_process = 1)
BEGIN
PRINT 'No active queries'
END
ELSE
BEGIN
IF @runtime IS NULL or @runtime_utc IS NULL
BEGIN
SET @runtime = GETDATE()
SET @runtime_utc = GETUTCDATE()
END
print ''
print '-- high_io_queries --'
select CONVERT (varchar(30), @runtime, 126) as runtime, CONVERT (varchar(30), @runtime_utc, 126) as runtime_utc, req.session_id, req.start_time as request_start_time, req.cpu_time, req.total_elapsed_time, req.logical_reads,
req.status, req.command, req.wait_type, req.wait_time, req.scheduler_id, req.granted_query_memory, tsk.task_state, tsk.context_switches_count,
replace(replace(substring(ISNULL(SQLText.text, ''),1,1000),CHAR(10), ' '),CHAR(13), ' ') as batch_text,
ISNULL(sess.program_name, '') as program_name, ISNULL (sess.host_name, '') as Host_name, ISNULL(sess.host_process_id,0) as session_process_id,
ISNULL (conn.net_packet_size, 0) AS 'net_packet_size', LEFT (ISNULL (conn.client_net_address, ''), 20) AS 'client_net_address',
substring
(REPLACE
(REPLACE
(SUBSTRING
(SQLText.text
, (req.statement_start_offset/2) + 1
, (
(CASE statement_END_offset
WHEN -1
THEN DATALENGTH(SQLText.text)
ELSE req.statement_END_offset
END
- req.statement_start_offset)/2) + 1)
, CHAR(10), ' '), CHAR(13), ' '), 1, 512) AS active_statement_text
from sys.dm_exec_requests req
LEFT OUTER JOIN sys.dm_exec_connections conn on conn.session_id = req.session_id
OUTER APPLY sys.dm_exec_sql_text (ISNULL (req.sql_handle, conn.most_recent_sql_handle)) as SQLText
left outer join sys.dm_exec_sessions sess on conn.session_id = sess.session_id
left outer join sys.dm_os_tasks tsk on sess.session_id = tsk.session_id
where sess.is_user_process = 1
and wait_type IN ( 'PAGEIOLATCH_SH', 'PAGEIOLATCH_EX', 'PAGEIOLATCH_UP', 'WRITELOG','IO_COMPLETION','ASYNC_IO_COMPLETION' )
AND wait_time >= 15
ORDER BY req.logical_reads desc
OPTION (max_grant_percent = 3, MAXDOP 1)
PRINT ''
PRINT '-- sys.dm_io_pending_io_requests --'
DECLARE @sql_major_version INT, @sql_major_build INT, @sql NVARCHAR (max)
SELECT @sql_major_version = (CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS VARCHAR(20)), 4) AS INT))
SET @sql = N'SELECT CONVERT (VARCHAR(30), @runtime, 121) AS runtime
,[io_completion_request_address]
,[io_type]
,[io_pending_ms_ticks]
,[io_pending]
,[io_completion_routine_address]
,[io_user_data_address]
,[scheduler_address]
,[io_handle]
,[io_offset]
'
IF (@sql_major_version >=12)
BEGIN
SET @sql = @sql + N',[io_handle_path]'
END
SET @sql = @sql + N' FROM sys.dm_io_pending_io_requests'
EXECUTE sp_executesql @sql,
N'@runtime DATETIME',
@runtime = @runtime;
--flush results to client
RAISERROR (' ', 0, 1) WITH NOWAIT
IF @runtime IS NULL or @runtime_utc IS NULL
BEGIN
SET @runtime = GETDATE()
SET @runtime_utc = GETUTCDATE()
END
END
print ''
print '-- high_io_queries --'
select CONVERT (varchar(30), @runtime, 126) as runtime, CONVERT (varchar(30), @runtime_utc, 126) as runtime_utc, req.session_id, req.start_time as request_start_time, req.cpu_time, req.total_elapsed_time, req.logical_reads,
req.status, req.command, req.wait_type, req.wait_time, req.scheduler_id, req.granted_query_memory, tsk.task_state, tsk.context_switches_count,
replace(replace(substring(ISNULL(SQLText.text, ''),1,1000),CHAR(10), ' '),CHAR(13), ' ') as batch_text,
ISNULL(sess.program_name, '') as program_name, ISNULL (sess.host_name, '') as Host_name, ISNULL(sess.host_process_id,0) as session_process_id,
ISNULL (conn.net_packet_size, 0) AS 'net_packet_size', LEFT (ISNULL (conn.client_net_address, ''), 20) AS 'client_net_address',
substring
(REPLACE
(REPLACE
(SUBSTRING
(SQLText.text
, (req.statement_start_offset/2) + 1
, (
(CASE statement_END_offset
WHEN -1
THEN DATALENGTH(SQLText.text)
ELSE req.statement_END_offset
END
- req.statement_start_offset)/2) + 1)
, CHAR(10), ' '), CHAR(13), ' '), 1, 512) AS active_statement_text
from sys.dm_exec_requests req
LEFT OUTER JOIN sys.dm_exec_connections conn on conn.session_id = req.session_id
OUTER APPLY sys.dm_exec_sql_text (ISNULL (req.sql_handle, conn.most_recent_sql_handle)) as SQLText
left outer join sys.dm_exec_sessions sess on conn.session_id = sess.session_id
left outer join sys.dm_os_tasks tsk on sess.session_id = tsk.session_id
where sess.is_user_process = 1
and wait_type IN ( 'PAGEIOLATCH_SH', 'PAGEIOLATCH_EX', 'PAGEIOLATCH_UP', 'WRITELOG','IO_COMPLETION','ASYNC_IO_COMPLETION' )
AND wait_time >= 15
ORDER BY req.logical_reads desc
OPTION (max_grant_percent = 3, MAXDOP 1)
--flush results to client
RAISERROR (' ', 0, 1) WITH NOWAIT
END
END TRY
BEGIN CATCH
PRINT 'Exception occured in: "' + OBJECT_NAME(@@PROCID) + '"'
PRINT 'Msg ' + isnull(cast(Error_Number() as nvarchar(50)), '') + ', Level ' + isnull(cast(Error_Severity() as nvarchar(50)),'') + ', State ' + isnull(cast(Error_State() as nvarchar(50)),'') + ', Server ' + @@servername + ', Line ' + isnull(cast(Error_Line() as nvarchar(50)),'') + char(10) + Error_Message() + char(10);
END CATCH
END
GO
@ -114,65 +151,67 @@ if object_id ('#sp_run_high_io_perfstats','p') is not null
drop procedure #sp_run_high_io_perfstats
go
create procedure #sp_run_high_io_perfstats
as
AS
BEGIN TRY
-- Main loop
-- Main loop
print 'starting high io perf stats script...'
set language us_english
print '-- script source --'
select 'high io perf stats script' as script_name
print ''
print '-- script and environment details --'
print 'name value'
print '------------------------ ---------------------------------------------------'
print 'sql server name ' + @@servername
print 'machine name ' + convert (varchar, serverproperty ('machinename'))
print 'sql version (sp) ' + convert (varchar, serverproperty ('productversion')) + ' (' + convert (varchar, serverproperty ('productlevel')) + ')'
print 'edition ' + convert (varchar, serverproperty ('edition'))
print 'script begin time ' + convert (varchar(30), getdate(), 126)
print 'current database ' + db_name()
print '@@spid ' + ltrim(str(@@spid))
print ''
print 'starting high io perf stats script...'
set language us_english
print '-- script source --'
select 'high io perf stats script' as script_name
print ''
print '-- script and environment details --'
print 'name value'
print '------------------------ ---------------------------------------------------'
print 'sql server name ' + @@servername
print 'machine name ' + convert (varchar, serverproperty ('machinename'))
print 'sql version (sp) ' + convert (varchar, serverproperty ('productversion')) + ' (' + convert (varchar, serverproperty ('productlevel')) + ')'
print 'edition ' + convert (varchar, serverproperty ('edition'))
print 'script begin time ' + convert (varchar(30), getdate(), 126)
print 'current database ' + db_name()
print '@@spid ' + ltrim(str(@@spid))
print ''
DECLARE @runtime datetime, @runtime_utc datetime, @prevruntime datetime
DECLARE @msg varchar(100)
DECLARE @counter bigint
SELECT @prevruntime = sqlserver_start_time from sys.dm_os_sys_info
--set prevtime to 5 min earlier, in case SQL just started
SET @prevruntime = DATEADD(SECOND, -300, @prevruntime)
SET @counter = 0
DECLARE @runtime datetime, @runtime_utc datetime, @prevruntime datetime
DECLARE @msg varchar(100)
DECLARE @counter bigint
WHILE (1=1)
BEGIN
BEGIN TRY
SET @runtime = GETDATE()
SET @runtime_utc = GETUTCDATE()
--SET @msg = 'Start time: ' + CONVERT (varchar(30), @runtime, 126)
SELECT @prevruntime = sqlserver_start_time from sys.dm_os_sys_info
--set prevtime to 5 min earlier, in case SQL just started
SET @prevruntime = DATEADD(SECOND, -300, @prevruntime)
SET @counter = 0
WHILE (1=1)
BEGIN
SET @runtime = GETDATE()
SET @runtime_utc = GETUTCDATE()
--SET @msg = 'Start time: ' + CONVERT (varchar(30), @runtime, 126)
PRINT ''
RAISERROR (@msg, 0, 1) WITH NOWAIT
if (@counter % 6 = 0) -- capture this data every 1 minute
BEGIN
exec #sp_perf_virtual_file_stats 'sqllogscout', @runtime = @runtime, @runtime_utc = @runtime_utc
END
-- Collect sp_perf_high_io_snapshot every 3 minutes
exec #sp_perf_io_snapshots 'sqllogscout', @runtime = @runtime, @runtime_utc = @runtime_utc
SET @prevruntime = @runtime
WAITFOR DELAY '0:00:10'
set @counter = @counter + 1
END
PRINT ''
RAISERROR (@msg, 0, 1) WITH NOWAIT
if (@counter % 6 = 0) -- capture this data every 1 minute
BEGIN
exec #sp_perf_virtual_file_stats 'sqllogscout', @runtime = @runtime, @runtime_utc = @runtime_utc
END
-- Collect sp_perf_high_io_snapshot every 3 minutes
exec #sp_perf_io_snapshots 'sqllogscout', @runtime = @runtime, @runtime_utc = @runtime_utc
SET @prevruntime = @runtime
WAITFOR DELAY '0:00:10'
set @counter = @counter + 1
END TRY
BEGIN CATCH
PRINT 'Exception occured in: "' + OBJECT_NAME(@@PROCID) + '"'
PRINT 'Msg ' + isnull(cast(Error_Number() as nvarchar(50)), '') + ', Level ' + isnull(cast(Error_Severity() as nvarchar(50)),'') + ', State ' + isnull(cast(Error_State() as nvarchar(50)),'') + ', Server ' + @@servername + ', Line ' + isnull(cast(Error_Line() as nvarchar(50)),'') + char(10) + Error_Message() + char(10);
END CATCH
END
END TRY
BEGIN CATCH
PRINT 'Exception occured in: "' + OBJECT_NAME(@@PROCID) + '"'
PRINT 'Msg ' + isnull(cast(Error_Number() as nvarchar(50)), '') + ', Level ' + isnull(cast(Error_Severity() as nvarchar(50)),'') + ', State ' + isnull(cast(Error_State() as nvarchar(50)),'') + ', Server ' + @@servername + ', Line ' + isnull(cast(Error_Line() as nvarchar(50)),'') + char(10) + Error_Message() + char(10);
END CATCH
GO
exec #sp_run_high_io_perfstats
exec #sp_run_high_io_perfstats

Просмотреть файл

@ -54,7 +54,7 @@ function Get-ClusterVnnPlusInstance([string]$instance)
if ($instance -eq "MSSQLSERVER"){
Write-LogDebug "VirtualName+Instance: " ($vnn) -DebugLogLevel 2
$VirtNetworkNamePlusInstance = ($vnn)
$VirtNetworkNamePlusInstance = $vnn
Write-LogDebug "Combined NetName+Instance: '$VirtNetworkNamePlusInstance'" -DebugLogLevel 2
}
@ -141,24 +141,27 @@ function IsFailoverClusteredInstance([string]$instanceName)
}
}
function Get-InstanceNamesOnly()
function Get-SQLServiceNameAndStatus()
{
Write-LogDebug "Inside" $MyInvocation.MyCommand
try
{
[string[]]$InstanceArray = @()
$selectedSqlInstance = ""
$InstanceArray = @()
#find the actively running SQL Server services
$sql_running_services = Get-Service | Where-Object {(($_.Name -match "MSSQL\$") -or ($_.Name -eq "MSSQLSERVER")) -and ($_.Status -eq "Running")} | Select-Object Name
$sql_services = Get-Service | Where-Object {(($_.Name -match "MSSQL\$") -or ($_.Name -eq "MSSQLSERVER"))} | ForEach-Object {[PSCustomObject]@{Name=$_.Name; Status=$_.Status.ToString()}}
if ($sql_running_services.Count -eq 0)
if ($sql_services.Count -eq 0)
{
#Insert dummy row in array to keep object type consistent
[PSCustomObject]$sql_services = @{Name='no_instance_found'; Status='UNKNOWN'}
Write-LogDebug "No installed SQL Server instances found. Array value: $sql_services" -DebugLogLevel 1
Write-LogInformation "There are currently no running instances of SQL Server. Would you like to proceed with OS-only log collection" -ForegroundColor Green
Write-LogInformation "There are currently no installed instances of SQL Server. Would you like to proceed with OS-only log collection?" -ForegroundColor Green
if ($global:gInteractivePrompts -eq "Noisy")
{
@ -184,7 +187,7 @@ function Get-InstanceNamesOnly()
if ($confirm -eq "Y")
{
$InstanceArray+=$global:sql_instance_conn_str
$InstanceArray+=$sql_services
}
elseif ($confirm -eq "N")
{
@ -197,27 +200,25 @@ function Get-InstanceNamesOnly()
else
{
Write-LogDebug ""
foreach ($sqlserver in $sql_running_services)
foreach ($sqlserver in $sql_services)
{
[string]$sqlinstance = $sqlserver.Name
Write-LogDebug "The SQL Server service array in foreach contains $sqlserver" -DebugLogLevel 3
#in the case of a default instance, just use MSSQLSERVER which is the instance name
if ($sqlinstance.IndexOf("$") -lt 1)
if ($sqlserver.Name -contains "$")
{
$selectedSqlInstance = $sqlinstance
Write-LogDebug "The SQL Server service array returned $sqlserver" -DebugLogLevel 3
$InstanceArray += $sqlserver
}
#for named instance, strip the part after the "$"
else
{
$selectedSqlInstance = $sqlinstance.Substring($sqlinstance.IndexOf("$") + 1)
Write-LogDebug "The SQL Server service named instance array returned $sqlserver" -DebugLogLevel 3
$sqlserver.Name = $sqlserver.Name -replace '.*\$',''
$InstanceArray += $sqlserver
Write-LogDebug "The SQL Server service named extracted instance array returned $sqlserver" -DebugLogLevel 3
}
#add each instance name to the array
$InstanceArray+=$selectedSqlInstance
}
}
@ -236,71 +237,92 @@ function Get-InstanceNamesOnly()
function Get-NetNameMatchingInstance()
{
Write-LogDebug "Inside" $MyInvocation.MyCommand
try
{
[string[]]$NetworkNamePlustInstanceArray = @()
$NetworkNamePlusInstanceArray = @()
$isClustered = $false
[string[]]$instanceArrayLocal = @()
#create dummy record in array and delete $NetworkNamePlusInstanceArray
#get the list of instance names and status of the service
[PSCustomObject]$InstanceNameAndStatusArray = Get-SQLServiceNameAndStatus
Write-LogDebug "The InstanceNameAndStatusArray is: $InstanceNameAndStatusArray" -DebugLogLevel 3
#get the list of instance names
$instanceArrayLocal = Get-InstanceNamesOnly
#special cases - if no SQL instance on the machine, just hard-code a value
if ($global:sql_instance_conn_str -eq $instanceArrayLocal.Get(0) )
foreach ($SQLInstance in $InstanceNameAndStatusArray)
{
$NetworkNamePlustInstanceArray+=$instanceArrayLocal.Get(0)
Write-LogDebug "No running SQL Server instances on the box so hard coding a value and collecting OS-data" -DebugLogLevel 1
}
elseif ($instanceArrayLocal -and ($null -ne $instanceArrayLocal))
{
Write-LogDebug "InstanceArrayLocal contains:" $instanceArrayLocal -DebugLogLevel 2
Write-LogDebug "Instance name and status: '$SQLInstance'" -DebugLogLevel 3
#build NetName + Instance
$isClustered = IsClustered #($instanceArrayLocal)
#if this is on a clustered system, then need to check for FCI or AG resources
if ($isClustered -eq $true)
#special cases - if no SQL instance on the machine, just hard-code a value
if ($global:sql_instance_conn_str -eq $SQLInstance.Name)
{
#loop through each instance name and check if FCI or not. If FCI, use ClusterVnnPlusInstance, else use HostnamePlusInstance
#append each name to the output array $NetworkNamePlustInstanceArray
for($i=0; $i -lt $instanceArrayLocal.Count; $i++)
$NetworkNamePlusInstanceArray+=@([PSCustomObject]@{Name=$SQLInstance.Name;Status='UNKNOWN'})
Write-LogDebug "No running SQL Server instances on the box so hard coding a value and collecting OS-data" -DebugLogLevel 1
}
elseif ($SQLInstance -and ($null -ne $SQLInstance))
{
Write-LogDebug "SQLInstance array contains:" $SQLInstance -DebugLogLevel 2
#build NetName + Instance
$isClustered = IsClustered #($InstanceNameAndStatusArray)
#if this is on a clustered system, then need to check for FCI or AG resources
if ($isClustered -eq $true)
{
if (IsFailoverClusteredInstance($instanceArrayLocal[$i]))
#loop through each instance name and check if FCI or not. If FCI, use ClusterVnnPlusInstance, else use HostnamePlusInstance
#append each name to the output array $NetworkNamePlusInstanceArray
if (IsFailoverClusteredInstance($SQLInstance.Name))
{
Write-LogDebug "The instance '$SQLInstance' is a SQL FCI" -DebugLogLevel 2
$SQLInstance.Name = Get-ClusterVnnPlusInstance($SQLInstance.Name)
$LogRec = $SQLInstance.Name
Write-LogDebug "The value of SQLInstance.Name $LogRec" -DebugLogLevel 3
Write-LogDebug "Temp FCI value is $SQLInstance" -DebugLogLevel 3
Write-LogDebug "The value of the array before change is $NetworkNamePlusInstanceArray" -DebugLogLevel 3
Write-LogDebug "The data type of the array before change is ($NetworkNamePlusInstanceArray.GetType())" -DebugLogLevel 3
Write-LogDebug "The value of the SQLInstance array before change is $SQLInstance" -DebugLogLevel 3
#This doesn't work for some reason
#$NetworkNamePlusInstanceArray += $SQLInstance
$NetworkNamePlusInstanceArray += @([PSCustomObject]$SQLInstance)
Write-LogDebug "The value of the SQLInstance array after change is $SQLInstance" -DebugLogLevel 3
Write-LogDebug "Result of FCI is $NetworkNamePlusInstanceArray" -DebugLogLevel 3
}
else
{
$NetworkNamePlustInstanceArray += Get-ClusterVnnPlusInstance ($instanceArrayLocal[$i])
Write-LogDebug "The instance '$SQLInstance' is a not SQL FCI but is clustered" -DebugLogLevel 2
$SQLInstance.Name = Get-HostnamePlusInstance($SQLInstance.Name)
$NetworkNamePlusInstanceArray += $SQLInstance
Write-LogDebug "Result of non-FCI Cluster is $NetworkNamePlusInstanceArray" -DebugLogLevel 3
}
else
{
$NetworkNamePlustInstanceArray += Get-HostnamePlusInstance($instanceArrayLocal[$i])
}
}
#all local resources so just build array with local instances
else
{
$TestLog = $SQLInstance.Name
Write-LogDebug "Array value is $SQLInstance" -DebugLogLevel 3
Write-LogDebug "Array value.name is $TestLog" -DebugLogLevel 3
$SQLInstance.Name = Get-HostnamePlusInstance($SQLInstance.Name)
Write-LogDebug "Array value after Get-HostnamePlusInstance is $SQLInstance" -DebugLogLevel 3
$NetworkNamePlusInstanceArray += $SQLInstance
}
}
#all local resources so just build array with local instances
else
{
for($i=0; $i -lt $instanceArrayLocal.Count; $i++)
{
$NetworkNamePlustInstanceArray += Get-HostnamePlusInstance($instanceArrayLocal[$i])
}
Write-LogError "InstanceArrayLocal array is blank or null - no instances populated for some reason"
}
}
else
{
Write-LogError "InstanceArrayLocal array is blank or null - no instances populated for some reason"
}
return $NetworkNamePlustInstanceArray
Write-LogDebug "The NetworkNamePlusInstanceArray in Get-NetNameMatchingInstance is: $NetworkNamePlusInstanceArray" -DebugLogLevel 3
return [PSCustomObject]$NetworkNamePlusInstanceArray
}
catch
{
@ -320,8 +342,7 @@ function Select-SQLServerForDiagnostics()
$SqlIdInt = 777
$isInt = $false
$ValidId = $false
[string[]]$NetNamePlusinstanceArray = @()
[string]$PickedNetPlusInstance = ""
$NetNamePlusinstanceArray = @()
if ($global:instance_independent_collection -eq $true)
{
@ -332,9 +353,8 @@ function Select-SQLServerForDiagnostics()
#ma Added
#$global:gui_mode
[bool]$isInstanceNameSelected = $false
IF (![string]::IsNullOrWhitespace($Global:ComboBoxInstanceName.Text))
if (![string]::IsNullOrWhitespace($Global:ComboBoxInstanceName.Text))
{
$portName = $Global:ComboBoxInstanceName.SelectedIndex
$SqlIdInt = $Global:ComboBoxInstanceName.SelectedIndex
$isInstanceNameSelected = $true
}
@ -342,43 +362,121 @@ function Select-SQLServerForDiagnostics()
#if SQL LogScout did not accept any values for parameter $ServerName
if (($true -eq [string]::IsNullOrWhiteSpace($global:gServerName)) -and $global:gServerName.Length -le 1 )
{
Write-LogDebug "Server Instance param is blank. Switching to auto-discovery of instances" -DebugLogLevel 2
Write-LogDebug "Server Instance param is blank. Switching to auto-discovery of instances" -DebugLogLevel 3
$NetNamePlusinstanceArray = Get-NetNameMatchingInstance
if ($NetNamePlusinstanceArray.get(0) -eq $global:sql_instance_conn_str)
Write-LogDebug "The NetNamePlusinstanceArray in discovery is: $NetNamePlusinstanceArray" -DebugLogLevel 3
if ($NetNamePlusinstanceArray.Name -eq $global:sql_instance_conn_str)
{
$hard_coded_instance = $NetNamePlusinstanceArray.Get(0)
Write-LogDebug "No running SQL Server instances, thus returning the default '$hard_coded_instance' and collecting OS-data only" -DebugLogLevel 1
$hard_coded_instance = $NetNamePlusinstanceArray.Name
Write-LogDebug "No running SQL Server instances, thus returning the default '$hard_coded_instance' and collecting OS-data only" -DebugLogLevel 3
return
}
elseif ($NetNamePlusinstanceArray -and ($null -ne $NetNamePlusinstanceArray))
elseif ($NetNamePlusinstanceArray.Name -and ($null -ne $NetNamePlusinstanceArray.Name))
{
Write-LogDebug "NetNamePlusinstanceArray contains: " $NetNamePlusinstanceArray -DebugLogLevel 4
Write-LogDebug "NetNamePlusinstanceArray contains: " $NetNamePlusinstanceArray -DebugLogLevel 3
#prompt the user to pick from the list
if ($NetNamePlusinstanceArray.Count -ge 1 -and !$isInstanceNameSelected)
$Count = $NetNamePlusinstanceArray.Count
Write-LogDebug "Count of NetNamePlusinstanceArray is $Count" -DebugLogLevel 3
Write-LogDebug "isInstanceNameSelected is $isInstanceNameSelected" -DebugLogLevel 3
if ($NetNamePlusinstanceArray.Count -ne 0 -and !$isInstanceNameSelected)
{
Write-LogDebug "NetNamePlusinstanceArray contains more than one instance. Prompting user to select one" -DebugLogLevel 3
$instanceIDArray = 0..($NetNamePlusinstanceArray.Length -1)
$instanceIDArray = 0..($NetNamePlusinstanceArray.Length -1)
#print out the instance names
Write-LogInformation "Discovered the following SQL Server instance(s)`n"
Write-LogInformation ""
Write-LogInformation "ID SQL Instance Name"
Write-LogInformation "-- ----------------"
# sort the array by instance name
$NetNamePlusinstanceArray = $NetNamePlusinstanceArray | Sort-Object
#TO DO - sory by property.
$NetNamePlusinstanceArray = $NetNamePlusinstanceArray | Sort-Object -Property Name
#TO DO - parse the file length out using something like $maxLength = ($array.Name | Measure-Object -Maximum -Property Length).Maximum. Need to calculate spaces based on values.
for($i=0; $i -lt $NetNamePlusinstanceArray.Count;$i++)
Write-LogDebug "NetNamePlusinstanceArray sorted contains: " $NetNamePlusinstanceArray -DebugLogLevel 4
#set spacing for displaying the text
#set hard-coded spacing for displaying the text
[string] $StaticGap = "".PadRight(3)
#GETTING PROMPT TO DISPLAY
## build the ID# header values
$IDHeader = "ID#"
#get the max length of the ID# values (for 2000 instances on the box the value would be 1999, and length will be 4 characters)
[int]$IDMaxLen = ($NetNamePlusinstanceArray.Count | ForEach-Object { [string]$_ } | Measure-Object -Maximum -Property Length).Maximum
#if the max value is less than the header length, then set the header be 3 characters long
if ($IDMaxLen -le $IDHeader.Length)
{
Write-LogInformation $i " " $NetNamePlusinstanceArray[$i]
[int]$IDMaxLen = $IDHeader.Length
}
Write-LogDebug "IDMaxLen is $IDMaxLen"
# create the header hyphens to go above the ID#
[string]$IDMaxHeader = '-' * $IDMaxLen
## build the instance name header values
[string]$InstanceNameHeader = "SQL Instance Name"
#get the max length of all the instances found the box (running or stopped)
[int]$SQLInstanceNameMaxLen = ($NetNamePlusinstanceArray.Name | ForEach-Object {[string]$_}| Measure-Object -Maximum -Property Length).Maximum
Write-LogDebug "SQLInstanceNameMaxLen value is $SQLInstanceNameMaxLen"
# if longest instance name is less than the defined header length, then pad to the header length and not instance length
if ($SQLInstanceNameMaxLen -le ($InstanceNameHeader.Length))
{
$SQLInstanceNameMaxLen = $InstanceNameHeader.Length
}
Write-LogDebug "SQLInstanceNameMaxLen is $SQLInstanceNameMaxLen"
# prepare the header hyphens to go above the instance name
[string]$SQLInstanceNameMaxHeader = '-' * $SQLInstanceNameMaxLen
## build the service status header values
$InstanceStatusHeader = "Status"
#get the max length of all the service status strings (running or stopped for now)
[int]$ServiceStatusMaxLen= ($NetNamePlusinstanceArray.Status | ForEach-Object {[string]$_} | Measure-Object -Maximum -Property Length).Maximum
if ($ServiceStatusMaxLen -le $InstanceStatusHeader.Length)
{
$ServiceStatusMaxLen = $InstanceStatusHeader.Length
}
Write-LogDebug "ServiceStatusMaxLen is $ServiceStatusMaxLen"
#prepare the header hyphens to go above service status
[string]$ServiceStatusMaxHeader = '-' * $ServiceStatusMaxLen
#display the header
Write-LogInformation "Discovered the following SQL Server instance(s)`n"
Write-LogInformation ""
Write-LogInformation "$($IDHeader+$StaticGap+$InstanceNameHeader.PadRight($SQLInstanceNameMaxLen)+$StaticGap+$InstanceStatusHeader.PadRight($ServiceStatusMaxLen))"
Write-LogInformation "$($IDMaxHeader+$StaticGap+$SQLInstanceNameMaxHeader+$StaticGap+$ServiceStatusMaxHeader)"
#loop through instances and append to cmd display
$i = 0
foreach ($FoundInstance in $NetNamePlusinstanceArray)
{
$InstanceName = $FoundInstance.Name
$InstanceStatus = $FoundInstance.Status
Write-LogDebug "Looping through $i, $InstanceName, $InstanceStatus" -DebugLogLevel 3
Write-LogInformation "$($i.ToString().PadRight($IdMaxLen)+$StaticGap+$InstanceName.PadRight($SQLInstanceNameMaxLen)+$StaticGap+$InstanceStatus.PadRight($ServiceStatusMaxWithSpace))"
#Write-LogInformation $i " " $FoundInstance.Name " " $FoundInstance.Status
$i++
}
#prompt the user to select an instance
while(($isInt -eq $false) -or ($ValidId -eq $false))
{
Write-LogInformation ""
@ -419,16 +517,18 @@ function Select-SQLServerForDiagnostics()
exit
}
$str = "You selected instance '" + $NetNamePlusinstanceArray[$SqlIdInt] +"' to collect diagnostic data. "
$str = "You selected instance '" + $NetNamePlusinstanceArray[$SqlIdInt].Name +"' to collect diagnostic data. "
Write-LogInformation $str -ForegroundColor Green
#set the global variable so it can be easily used by multiple collectors
$global:sql_instance_conn_str = $NetNamePlusinstanceArray[$SqlIdInt]
$global:sql_instance_conn_str = $NetNamePlusinstanceArray[$SqlIdInt].Name
$global:sql_instance_service_status = $NetNamePlusinstanceArray[$SqlIdInt].Status
Write-LogDebug "The SQL instance service status is updated to $global:sql_instance_service_status"
#return $NetNamePlusinstanceArray[$SqlIdInt]
}
# if the instance is passed in as a parameter, then use that value. But test if that instance is running/valid
else
{
Write-LogDebug "Server Instance param is '$($global:gServerName)'. Using this value for data collection" -DebugLogLevel 2
@ -449,7 +549,16 @@ function Select-SQLServerForDiagnostics()
{
$global:sql_instance_conn_str = $global:gServerName
}
#Get service status. Since user provided instance name, no instance discovery code invoked
if (Test-SQLConnection($global:sql_instance_conn_str))
{
$global:sql_instance_service_status = "Running"
}
else
{
$global:sql_instance_service_status = "UNKNOWN"
}
}
}

Просмотреть файл

@ -81,6 +81,10 @@ param(
Write-LogInformation ($CustomLogMessage + " " + $ret)
}
#Read-Host is the cause of resetting disableCtrlCAsInput so we need to check reset it after every use.
setDisableCtrlCasInput
return $ret
}

Просмотреть файл

@ -47,7 +47,7 @@
\MSSQL$*:Availability Replica(*)\*
\MSSQL$*:Backup Device\*
\MSSQL$*:Batch Resp Statistics(*)\*
\MSSQL$*:Broker Activation\*
\MSSQL$*:Broker Activation(*)\*
\MSSQL$*:Broker Statistics\*
\MSSQL$*:Broker TO Statistics\*
\MSSQL$*:Broker/DBM Transport\*
@ -152,9 +152,11 @@
\SQL Server 2022 XTP Phantom Processor(*)\*
\SQL Server 2022 XTP Transactions(*)\*
\System\*
\TCP\*
\TCPv4\*
\TCPv6\*
\Telephony\*
\UDP\*
\UDPv4\*
\UDPv6\*
\Web Service(_Total)\*
\Web Service(Administration Web Site)\*
\Web Service(Default Web Site)\*

Просмотреть файл

@ -0,0 +1,460 @@
SET NOCOUNT ON
PRINT ''
RAISERROR ('-- DiagInfo --', 0, 1) WITH NOWAIT
SELECT 1002 AS 'DiagVersion', '2023-12-06' AS 'DiagDate'
PRINT ''
PRINT 'Script Version = 1001'
PRINT ''
SET LANGUAGE us_english
PRINT '-- Script and Environment Details --'
PRINT 'Name Value'
PRINT '------------------------ ---------------------------------------------------'
PRINT 'Script Name Misc Diagnostics Info'
PRINT 'Script File Name $File: MiscDiagInfo.sql $'
PRINT 'Revision $Revision: 1 $ ($Change: ? $)'
PRINT 'Last Modified $Date: 2023/12/06 12:04:00 EST $'
PRINT 'Script Begin Time ' + CONVERT (VARCHAR(30), GETDATE(), 126)
PRINT 'Current Database ' + DB_NAME()
PRINT ''
DECLARE @sql_major_version INT, @sql_major_build INT, @sql NVARCHAR(max), @sql_minor_version INT
SELECT @sql_major_version = (CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS VARCHAR(20)), 4) AS INT)),
@sql_major_build = (CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS VARCHAR(20)), 2) AS INT)) ,
@sql_minor_version = (CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS VARCHAR(20)), 3) AS INT))
-- ParsName is used to extract MajorVersion , MinorVersion and Build from ProductVersion e.g. 16.0.1105.1 will comeback AS 16000001105
DECLARE @SQLVERSION BIGINT = PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS VARCHAR(20)), 4)
+ RIGHT(REPLICATE ('0', 3) + PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS VARCHAR(20)), 3), 3)
+ RIGHT (replicate ('0', 6) + PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS VARCHAR(20)), 2) , 6)
CREATE TABLE #summary (PropertyName NVARCHAR(50) primary key, PropertyValue NVARCHAR(256))
INSERT INTO #summary VALUES ('ProductVersion', cast (SERVERPROPERTY('ProductVersion') AS NVARCHAR(max)))
INSERT INTO #summary VALUES ('MajorVersion', LEFT(CONVERT(SYSNAME,SERVERPROPERTY('ProductVersion')), CHARINDEX('.', CONVERT(SYSNAME,SERVERPROPERTY('ProductVersion')), 0)-1))
INSERT INTO #summary VALUES ('IsClustered', cast (SERVERPROPERTY('IsClustered') AS NVARCHAR(max)))
INSERT INTO #summary VALUES ('Edition', cast (SERVERPROPERTY('Edition') AS NVARCHAR(max)))
INSERT INTO #summary VALUES ('InstanceName', cast (SERVERPROPERTY('InstanceName') AS NVARCHAR(max)))
INSERT INTO #summary VALUES ('SQLServerName', @@SERVERNAME)
INSERT INTO #summary VALUES ('MachineName', cast (SERVERPROPERTY('MachineName') AS NVARCHAR(max)))
INSERT INTO #summary VALUES ('ProcessID', cast (SERVERPROPERTY('ProcessID') AS NVARCHAR(max)))
INSERT INTO #summary VALUES ('ResourceVersion', cast (SERVERPROPERTY('ResourceVersion') AS NVARCHAR(max)))
INSERT INTO #summary VALUES ('ServerName', cast (SERVERPROPERTY('ServerName') AS NVARCHAR(max)))
INSERT INTO #summary VALUES ('ComputerNamePhysicalNetBIOS', cast (SERVERPROPERTY('ComputerNamePhysicalNetBIOS') AS NVARCHAR(max)))
INSERT INTO #summary VALUES ('BuildClrVersion', cast (SERVERPROPERTY('BuildClrVersion') AS NVARCHAR(max)))
INSERT INTO #summary VALUES ('IsFullTextInstalled', cast (SERVERPROPERTY('IsFullTextInstalled') AS NVARCHAR(max)))
INSERT INTO #summary VALUES ('IsIntegratedSecurityOnly', cast (SERVERPROPERTY('IsIntegratedSecurityOnly') AS NVARCHAR(max)))
INSERT INTO #summary VALUES ('ProductLevel', cast (SERVERPROPERTY('ProductLevel') AS NVARCHAR(max)))
INSERT INTO #summary VALUES ('suser_name()', cast (SUSER_NAME() AS NVARCHAR(max)))
INSERT INTO #summary SELECT 'number of visible schedulers', count (*) 'cnt' FROM sys.dm_os_schedulers WHERE status = 'VISIBLE ONLINE'
INSERT INTO #summary SELECT 'number of visible numa nodes', count (distinct parent_node_id) 'cnt' FROM sys.dm_os_schedulers WHERE status = 'VISIBLE ONLINE'
INSERT INTO #summary SELECT 'cpu_count', cpu_count FROM sys.dm_os_sys_info
INSERT INTO #summary SELECT 'hyperthread_ratio', hyperthread_ratio FROM sys.dm_os_sys_info
INSERT INTO #summary SELECT 'machine start time', convert(VARCHAR(23),dateadd(SECOND, -ms_ticks/1000, GETDATE()),121) FROM sys.dm_os_sys_info
INSERT INTO #summary SELECT 'number of tempdb data files', count (*) 'cnt' FROM master.sys.master_files WHERE database_id = 2 and [type] = 0
INSERT INTO #summary SELECT 'number of active profiler traces',count(*) 'cnt' FROM ::fn_trace_getinfo(0) WHERE property = 5 and convert(TINYINT,value) = 1
INSERT INTO #summary SELECT 'suser_name() default database name',default_database_name FROM sys.server_principals WHERE name = SUSER_NAME()
INSERT INTO #summary SELECT 'VISIBLEONLINE_SCHEDULER_COUNT' PropertyName, count (*) PropertValue FROM sys.dm_os_schedulers WHERE status='VISIBLE ONLINE'
INSERT INTO #summary SELECT 'UTCOffset_in_Hours' PropertyName, cast( datediff (MINUTE, getutcdate(), getdate()) / 60.0 AS decimal(10,2)) PropertyValue
DECLARE @cpu_ticks BIGINT
SELECT @cpu_ticks = cpu_ticks FROM sys.dm_os_sys_info
WAITFOR DELAY '0:0:2'
SELECT @cpu_ticks = cpu_ticks - @cpu_ticks FROM sys.dm_os_sys_info
INSERT INTO #summary VALUES ('cpu_ticks_per_sec', @cpu_ticks / 2 )
PRINT ''
-- GO
--removing xp_instance_regread calls & related variables as a part of issue #149
DECLARE @value NVARCHAR(256)
DECLARE @pos INT
--get windows info from dmv
SELECT @value = windows_release FROM sys.dm_os_windows_info
SET @pos = CHARINDEX(N'.', @value)
IF @pos != 0
BEGIN
INSERT INTO #summary VALUES ('operating system version major',SUBSTRING(@value, 1, @pos-1))
INSERT INTO #summary VALUES ('operating system version minor',SUBSTRING(@value, @pos+1, LEN(@value)))
--inserting NULL to keep same #summary structure
INSERT INTO #summary VALUES ('operating system version build', NULL)
INSERT INTO #summary VALUES ('operating system', NULL)
INSERT INTO #summary VALUES ('operating system install date',NULL)
END
--inserting NULL to keep same #summary structure
INSERT INTO #summary VALUES ('registry SystemManufacturer', NULL)
INSERT INTO #summary VALUES ('registry SystemProductName', NULL)
INSERT INTO #summary VALUES ('registry ActivePowerScheme (default)', NULL)
INSERT INTO #summary VALUES ('registry ActivePowerScheme', NULL)
--inserting OS Edition and Build from @@Version
INSERT INTO #summary VALUES ('OS Edition and Build from @@Version', REPLACE(LTRIM(SUBSTRING(@@VERSION,CHARINDEX(' on ',@@VERSION)+3,100)),CHAR(10),''))
IF (@SQLVERSION >= 10000001600) --10.0.1600
BEGIN
EXEC sp_executesql N'INSERT INTO #summary SELECT ''sqlserver_start_time'', convert(VARCHAR(23),sqlserver_start_time,121) FROM sys.dm_os_sys_info'
EXEC sp_executesql N'INSERT INTO #summary SELECT ''resource governor enabled'', is_enabled FROM sys.resource_governor_configuration'
INSERT INTO #summary VALUES ('FilestreamShareName', cast (SERVERPROPERTY('FilestreamShareName') AS NVARCHAR(max)))
INSERT INTO #summary VALUES ('FilestreamConfiguredLevel', cast (SERVERPROPERTY('FilestreamConfiguredLevel') AS NVARCHAR(max)))
INSERT INTO #summary VALUES ('FilestreamEffectiveLevel', cast (SERVERPROPERTY('FilestreamEffectiveLevel') AS NVARCHAR(max)))
INSERT INTO #summary SELECT 'number of active extENDed event traces',count(*) AS 'cnt' FROM sys.dm_xe_sessions
END
IF (@SQLVERSION >= 10050001600) --10.50.1600
BEGIN
EXEC sp_executesql N'INSERT INTO #summary SELECT ''possibly running in virtual machine'', virtual_machine_type FROM sys.dm_os_sys_info'
END
IF (@SQLVERSION >= 11000002100) --11.0.2100
BEGIN
EXEC sp_executesql N'INSERT INTO #summary SELECT ''physical_memory_kb'', physical_memory_kb FROM sys.dm_os_sys_info'
INSERT INTO #summary VALUES ('HadrManagerStatus', cast (SERVERPROPERTY('HadrManagerStatus') AS NVARCHAR(max)))
INSERT INTO #summary VALUES ('IsHadrEnabled', cast (SERVERPROPERTY('IsHadrEnabled') AS NVARCHAR(max)))
INSERT INTO #summary SELECT 'instant_file_initialization_enabled', instant_file_initialization_enabled FROM sys.dm_server_services WHERE process_id = SERVERPROPERTY('ProcessID')
END
IF (@SQLVERSION >= 12000002000) --12.0.2000
BEGIN
INSERT INTO #summary VALUES ('IsLocalDB', cast (SERVERPROPERTY('IsLocalDB') AS NVARCHAR(max)))
INSERT INTO #summary VALUES ('IsXTPSupported', cast (SERVERPROPERTY('IsXTPSupported') AS NVARCHAR(max)))
END
RAISERROR ('--ServerProperty--', 0, 1) WITH NOWAIT
SELECT * FROM #summary
ORDER BY PropertyName
DROP TABLE #summary
PRINT ''
--GO
--changing xp_instance_regenumvalues to dmv access as a part of issue #149
DECLARE @startup table (ArgsName NVARCHAR(10), ArgsValue NVARCHAR(max))
INSERT INTO @startup
SELECT sReg.value_name, CAST(sReg.value_data AS NVARCHAR(max))
FROM sys.dm_server_registry AS sReg
WHERE sReg.value_name LIKE N'SQLArg%';
RAISERROR ('--Startup Parameters--', 0, 1) WITH NOWAIT
SELECT * FROM @startup
PRINT ''
CREATE TABLE #traceflg (TraceFlag INT, Status INT, Global INT, Session INT)
INSERT INTO #traceflg EXEC ('dbcc tracestatus (-1)')
PRINT ''
RAISERROR ('--traceflags--', 0, 1) WITH NOWAIT
SELECT * FROM #traceflg
DROP TABLE #traceflg
PRINT ''
RAISERROR ('--sys.dm_os_schedulers--', 0, 1) WITH NOWAIT
SELECT * FROM sys.dm_os_schedulers
PRINT ''
RAISERROR ('-- sys.dm_os_loaded_modules --', 0, 1) WITH NOWAIT
SELECT base_address ,
file_version,
product_version,
debug,
patched,
prerelease,
private_build,
special_build,
[language],
company,
[description],
[name]
FROM sys.dm_os_loaded_modules
PRINT ''
IF (@SQLVERSION >= 10000001600 --10.0.1600
and @SQLVERSION < 10050000000) --10.50.0.0
BEGIN
PRINT ''
RAISERROR ('--sys.dm_os_nodes--', 0, 1) WITH NOWAIT
EXEC sp_executesql N'SELECT node_id, memory_object_address, memory_clerk_address, io_completion_worker_address, memory_node_id, cpu_affinity_mask, online_scheduler_count, idle_scheduler_count active_worker_count, avg_load_balance, timer_task_affinity_mask, permanent_task_affinity_mask, resource_monitor_state, node_state_desc FROM sys.dm_os_nodes'
END
IF (@SQLVERSION >= 10050000000) --10.50.0.0
BEGIN
PRINT ''
RAISERROR ('--sys.dm_os_nodes--', 0, 1) WITH NOWAIT
EXEC sp_executesql N'SELECT node_id, memory_object_address, memory_clerk_address, io_completion_worker_address, memory_node_id, cpu_affinity_mask, online_scheduler_count, idle_scheduler_count active_worker_count, avg_load_balance, timer_task_affinity_mask, permanent_task_affinity_mask, resource_monitor_state, online_scheduler_mask, processor_group, node_state_desc FROM sys.dm_os_nodes'
END
PRINT ''
RAISERROR ('--dm_os_sys_info--', 0, 1) WITH NOWAIT
SELECT * FROM sys.dm_os_sys_info
if cast (SERVERPROPERTY('IsClustered') AS INT) = 1
BEGIN
PRINT ''
RAISERROR ('--fn_virtualservernodes--', 0, 1) WITH NOWAIT
SELECT * FROM fn_virtualservernodes()
END
PRINT ''
RAISERROR ('--sys.configurations--', 0, 1) WITH NOWAIT
SELECT configuration_id,
convert(INT,value) AS 'value',
convert(INT,value_in_use) AS 'value_in_use',
convert(INT,minimum) AS 'minimum',
convert(INT,maximum) AS 'maximum',
convert(INT,is_dynamic) AS 'is_dynamic',
convert(INT,is_advanced) AS 'is_advanced',
name
FROM sys.configurations
ORDER BY name
PRINT ''
RAISERROR ('--database files--', 0, 1) WITH NOWAIT
SELECT database_id, [file_id], file_guid, [type], LEFT(type_desc,10) AS 'type_desc', data_space_id, [state], LEFT(state_desc,16) AS 'state_desc', size, max_size, growth,
is_media_read_only, is_read_only, is_sparse, is_percent_growth, is_name_reserved, create_lsn, drop_lsn, read_only_lsn, read_write_lsn, differential_base_lsn, differential_base_guid,
differential_base_time, redo_start_lsn, redo_start_fork_guid, redo_target_lsn, redo_target_fork_guid, backup_lsn, db_name(database_id) AS 'Database_name', name, physical_name
FROM master.sys.master_files ORDER BY database_id, type, file_id
PRINT ''
RAISERROR ('-- sysaltfiles--', 0, 1) WITH NOWAIT
SELECT af.dbid as [dbid], db_name(af.dbid) as [database_name], fileid, groupid, [size], [maxsize], [growth], [status],rtrim(af.filename) as [filename],rtrim(af.name) as [filename]
FROM master.sys.sysaltfiles af
WHERE af.dbid != db_id('tempdb')
ORDER BY af.dbid,af.fileid
PRINT ''
RAISERROR ('--sys.databases_ex--', 0, 1) WITH NOWAIT
SELECT cast(DATABASEPROPERTYEX (name,'IsAutoCreateStatistics') AS INT) 'IsAutoCreateStatistics', cast( DATABASEPROPERTYEX (name,'IsAutoUpdateStatistics') AS INT) 'IsAutoUpdateStatistics', cast (DATABASEPROPERTYEX (name,'IsAutoCreateStatisticsIncremental') AS INT) 'IsAutoCreateStatisticsIncremental', * FROM sys.databases
PRINT ''
RAISERROR ('-- Windows Group Default Databases other than master --', 0, 1) WITH NOWAIT
SELECT name,default_database_name FROM sys.server_principals WHERE [type] = 'G' and is_disabled = 0 and default_database_name != 'master'
--removed AG related dmvs as a part of issue #162
PRINT ''
PRINT '-- sys.change_tracking_databases --'
SELECT * FROM sys.change_tracking_databases
PRINT ''
PRINT '-- sys.dm_database_encryption_keys --'
SELECT database_id, encryption_state FROM sys.dm_database_encryption_keys
PRINT ''
IF @SQLVERSION >= 15000002000 --15.0.2000
BEGIN
PRINT '-- sys.dm_tran_persistent_version_store_stats --'
SELECT * FROM sys.dm_tran_persistent_version_store_stats
PRINT ''
END
PRINT '-- sys.certificates --'
SELECT
CONVERT(VARCHAR(64),DB_NAME()) AS [database_name],
name,
certificate_id,
principal_id,
pvt_key_encryption_type,
CONVERT(VARCHAR(32), pvt_key_encryption_type_desc) AS pvt_key_encryption_type_desc,
is_active_for_begin_dialog,
CONVERT(VARCHAR(512), issuer_name) AS issuer_name,
cert_serial_number,
sid,
string_sid,
CONVERT(VARCHAR(512),subject) AS subject,
expiry_date,
start_date,
'0x' + CONVERT(VARCHAR(64),thumbprint,2) AS thumbprint,
CONVERT(VARCHAR(256), attested_by) AS attested_by,
pvt_key_last_backup_date
FROM master.sys.certificates
PRINT ''
--this proc is only present in SQL Server 2019 and later but seems not present in early builds
IF OBJECT_ID('sys.sp_certificate_issuers') IS NOT NULL
BEGIN
CREATE TABLE #certificate_issuers(
certificateid INT,
dnsname NVARCHAR(128) )
INSERT INTO #certificate_issuers
EXEC ('EXEC sys.sp_certificate_issuers')
PRINT '-- sys_sp_certificate_issuers --'
SELECT certificateid, dnsname
FROM #certificate_issuers
DROP TABLE #certificate_issuers
END
PRINT ''
PRINT ''
-- Collect db_log_info to check for VLF issues
--this table to be used by older versions of SQL Server prior to 2016 SP2
CREATE TABLE #dbcc_loginfo_cur_db
(
RecoveryUnitId INT,
FileId INT,
FileSize BIGINT,
StartOffset BIGINT,
FSeqNo BIGINT,
Status INT,
Parity INT,
CreateLSN NVARCHAR(48)
)
--this table contains all the results
CREATE TABLE #loginfo_all_dbs
(
database_id INT,
[database_name] VARCHAR(64),
vlf_count INT,
vlf_avg_size_mb DECIMAL(10,2),
vlf_min_size_mb DECIMAL(10,2),
vlf_max_size_mb DECIMAL(10,2),
vlf_status INT,
vlf_active BIT
)
DECLARE @dbname NVARCHAR(64), @dbid INT
DECLARE @dbcc_log_info VARCHAR(MAX)
DECLARE Database_Cursor CURSOR FOR SELECT database_id, name FROM MASTER.sys.databases
OPEN Database_Cursor;
FETCH NEXT FROM Database_Cursor INTO @dbid, @dbname;
WHILE @@FETCH_STATUS = 0
BEGIN
SET @dbcc_log_info = 'DBCC LOGINFO (''' + @dbname + ''') WITH NO_INFOMSGS'
IF ((@sql_major_version >= 14) or (@sql_major_version >= 13) and (@sql_major_build >= 5026 ))
BEGIN
INSERT INTO #loginfo_all_dbs(
database_id ,
database_name ,
vlf_count,
vlf_avg_size_mb ,
vlf_min_size_mb,
vlf_max_size_mb,
vlf_status ,
vlf_active)
SELECT
database_id,
@dbname,
count(*) AS vlf_count,
AVG(vlf_size_mb) AS vlf_avg_size_mb,
MIN(vlf_size_mb) AS vlf_min_size_mb,
MAX(vlf_size_mb) AS vlf_max_size_mb,
vlf_status,
vlf_active
FROM sys.dm_db_log_info (db_id(@dbname))
GROUP BY database_id, vlf_status, vlf_active
END
ELSE
--if version is prior to SQL 2016 SP2, use DBCC LOGINFO to get the data
--but insert and format it into a table as if it came from sys.dm_db_log_info
BEGIN
INSERT INTO #dbcc_loginfo_cur_db (
RecoveryUnitId ,
FileId ,
FileSize ,
StartOffset ,
FSeqNo ,
Status ,
Parity ,
CreateLSN)
EXEC(@dbcc_log_info)
INSERT INTO #loginfo_all_dbs(
database_id ,
database_name ,
vlf_count ,
vlf_avg_size_mb ,
vlf_min_size_mb,
vlf_max_size_mb,
vlf_status ,
vlf_active )
--do the formatting to match the sys.dm_db_log_info standard as much as possible
SELECT
@dbid,
@dbname,
COUNT(li.FSeqNo) AS vlf_count,
CONVERT(DECIMAL(10,2),AVG(li.FileSize/1024/1024.0)) AS vlf_avg_size_mb,
CONVERT(DECIMAL(10,2),MIN(li.FileSize/1024/1024.0)) AS vlf_min_size_mb,
CONVERT(DECIMAL(10,2),MAX(li.FileSize/1024/1024.0)) AS vlf_max_size_mb,
li.Status,
CASE WHEN li.Status = 2 THEN 1 ELSE 0 END AS Active
FROM #dbcc_loginfo_cur_db li
GROUP BY Status, CASE WHEN li.Status = 2 THEN 1 ELSE 0 END
--clean up the temp table for next loop
TRUNCATE TABLE #dbcc_loginfo_cur_db
END
FETCH NEXT FROM Database_Cursor INTO @dbid, @dbname;
END;
CLOSE Database_Cursor;
DEALLOCATE Database_Cursor;
PRINT '-- sys_dm_db_log_info --'
SELECT
database_id ,
database_name ,
vlf_count ,
vlf_avg_size_mb ,
vlf_min_size_mb ,
vlf_max_size_mb ,
vlf_status ,
vlf_active
FROM #loginfo_all_dbs
ORDER BY database_name
DROP TABLE #dbcc_loginfo_cur_db
DROP TABLE #loginfo_all_dbs
PRINT ''

Просмотреть файл

@ -1,446 +0,0 @@
set nocount on
go
print ''
RAISERROR ('-- DiagInfo --', 0, 1) WITH NOWAIT
select 1001 as 'DiagVersion', '2015-01-09' as 'DiagDate'
print ''
go
print 'Script Version = 1001'
print ''
go
SET LANGUAGE us_english
PRINT '-- Script and Environment Details --'
PRINT 'Name Value'
PRINT '------------------------ ---------------------------------------------------'
PRINT 'Script Name Misc Pssdiag Info'
PRINT 'Script File Name $File: MiscPssdiagInfo.sql $'
PRINT 'Revision $Revision: 1 $ ($Change: ? $)'
PRINT 'Last Modified $Date: 2015/01/26 12:04:00 EST $'
PRINT 'Script Begin Time ' + CONVERT (varchar(30), GETDATE(), 126)
PRINT 'Current Database ' + DB_NAME()
PRINT ''
GO
DECLARE @sql_major_version INT, @sql_major_build INT, @sql NVARCHAR(max)
SELECT @sql_major_version = (CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS varchar(20)), 4) AS INT)),
@sql_major_build = (CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS varchar(20)), 2) AS INT))
create table #summary (PropertyName nvarchar(50) primary key, PropertyValue nvarchar(256))
insert into #summary values ('ProductVersion', cast (SERVERPROPERTY('ProductVersion') as nvarchar(max)))
insert into #summary values ('MajorVersion', LEFT(CONVERT(SYSNAME,SERVERPROPERTY('ProductVersion')), CHARINDEX('.', CONVERT(SYSNAME,SERVERPROPERTY('ProductVersion')), 0)-1))
insert into #summary values ('IsClustered', cast (SERVERPROPERTY('IsClustered') as nvarchar(max)))
insert into #summary values ('Edition', cast (SERVERPROPERTY('Edition') as nvarchar(max)))
insert into #summary values ('InstanceName', cast (SERVERPROPERTY('InstanceName') as nvarchar(max)))
insert into #summary values ('SQLServerName', @@SERVERNAME)
insert into #summary values ('MachineName', cast (SERVERPROPERTY('MachineName') as nvarchar(max)))
insert into #summary values ('ProcessID', cast (SERVERPROPERTY('ProcessID') as nvarchar(max)))
insert into #summary values ('ResourceVersion', cast (SERVERPROPERTY('ResourceVersion') as nvarchar(max)))
insert into #summary values ('ServerName', cast (SERVERPROPERTY('ServerName') as nvarchar(max)))
insert into #summary values ('ComputerNamePhysicalNetBIOS', cast (SERVERPROPERTY('ComputerNamePhysicalNetBIOS') as nvarchar(max)))
insert into #summary values ('BuildClrVersion', cast (SERVERPROPERTY('BuildClrVersion') as nvarchar(max)))
insert into #summary values ('IsFullTextInstalled', cast (SERVERPROPERTY('IsFullTextInstalled') as nvarchar(max)))
insert into #summary values ('IsIntegratedSecurityOnly', cast (SERVERPROPERTY('IsIntegratedSecurityOnly') as nvarchar(max)))
insert into #summary values ('ProductLevel', cast (SERVERPROPERTY('ProductLevel') as nvarchar(max)))
insert into #summary values ('suser_name()', cast (SUSER_NAME() as nvarchar(max)))
insert into #summary select 'number of visible schedulers', count (*) 'cnt' from sys.dm_os_schedulers where status = 'VISIBLE ONLINE'
insert into #summary select 'number of visible numa nodes', count (distinct parent_node_id) 'cnt' from sys.dm_os_schedulers where status = 'VISIBLE ONLINE'
insert into #summary select 'cpu_count', cpu_count from sys.dm_os_sys_info
insert into #summary select 'hyperthread_ratio', hyperthread_ratio from sys.dm_os_sys_info
insert into #summary select 'machine start time', convert(varchar(23),dateadd(SECOND, -ms_ticks/1000, GETDATE()),121) from sys.dm_os_sys_info
insert into #summary select 'number of tempdb data files', count (*) 'cnt' from master.sys.master_files where database_id = 2 and [type] = 0
insert into #summary select 'number of active profiler traces',count(*) 'cnt' from ::fn_trace_getinfo(0) where property = 5 and convert(tinyint,value) = 1
insert into #summary select 'suser_name() default database name',default_database_name from sys.server_principals where name = SUSER_NAME()
insert into #summary select 'VISIBLEONLINE_SCHEDULER_COUNT' PropertyName, count (*) PropertValue from sys.dm_os_schedulers where status='VISIBLE ONLINE'
insert into #summary select 'UTCOffset_in_Hours' PropertyName, cast( datediff (MINUTE, getutcdate(), getdate()) / 60.0 as decimal(10,2)) PropertyValue
declare @cpu_ticks bigint
select @cpu_ticks = cpu_ticks from sys.dm_os_sys_info
waitfor delay '0:0:2'
select @cpu_ticks = cpu_ticks - @cpu_ticks from sys.dm_os_sys_info
insert into #summary values ('cpu_ticks_per_sec', @cpu_ticks / 2 )
PRINT ''
GO
--removing xp_instance_regread calls & related variables as a part of issue #149
DECLARE @value NVARCHAR(256)
DECLARE @pos INT
--get windows info from dmv
SELECT @value = windows_release FROM sys.dm_os_windows_info
SET @pos = CHARINDEX(N'.', @value)
IF @pos != 0
BEGIN
INSERT INTO #summary VALUES ('operating system version major',SUBSTRING(@value, 1, @pos-1))
INSERT INTO #summary VALUES ('operating system version minor',SUBSTRING(@value, @pos+1, LEN(@value)))
--inserting NULL to keep same #summary structure
INSERT INTO #summary VALUES ('operating system version build', NULL)
INSERT INTO #summary VALUES ('operating system', NULL)
INSERT INTO #summary VALUES ('operating system install date',NULL)
END
--inserting NULL to keep same #summary structure
INSERT INTO #summary VALUES ('registry SystemManufacturer', NULL)
INSERT INTO #summary VALUES ('registry SystemProductName', NULL)
INSERT INTO #summary VALUES ('registry ActivePowerScheme (default)', NULL)
INSERT INTO #summary VALUES ('registry ActivePowerScheme', NULL)
--inserting OS Edition and Build from @@Version
INSERT INTO #summary VALUES ('OS Edition and Build from @@Version', REPLACE(LTRIM(SUBSTRING(@@VERSION,CHARINDEX(' on ',@@VERSION)+3,100)),CHAR(10),''))
IF (@@MICROSOFTVERSION >= 167773760) --10.0.1600
begin
exec sp_executesql N'insert into #summary select ''sqlserver_start_time'', convert(varchar(23),sqlserver_start_time,121) from sys.dm_os_sys_info'
exec sp_executesql N'insert into #summary select ''resource governor enabled'', is_enabled from sys.resource_governor_configuration'
insert into #summary values ('FilestreamShareName', cast (SERVERPROPERTY('FilestreamShareName') as nvarchar(max)))
insert into #summary values ('FilestreamConfiguredLevel', cast (SERVERPROPERTY('FilestreamConfiguredLevel') as nvarchar(max)))
insert into #summary values ('FilestreamEffectiveLevel', cast (SERVERPROPERTY('FilestreamEffectiveLevel') as nvarchar(max)))
insert into #summary select 'number of active extended event traces',count(*) as 'cnt' from sys.dm_xe_sessions
end
IF (@@MICROSOFTVERSION >= 171050560) --10.50.1600
begin
exec sp_executesql N'insert into #summary select ''possibly running in virtual machine'', virtual_machine_type from sys.dm_os_sys_info'
end
IF (@@MICROSOFTVERSION >= 184551476) --11.0.2100
begin
exec sp_executesql N'insert into #summary select ''physical_memory_kb'', physical_memory_kb from sys.dm_os_sys_info'
insert into #summary values ('HadrManagerStatus', cast (SERVERPROPERTY('HadrManagerStatus') as nvarchar(max)))
insert into #summary values ('IsHadrEnabled', cast (SERVERPROPERTY('IsHadrEnabled') as nvarchar(max)))
insert into #summary SELECT 'instant_file_initialization_enabled', instant_file_initialization_enabled from sys.dm_server_services where process_id = SERVERPROPERTY('ProcessID')
end
IF (@@MICROSOFTVERSION >= 201328592) --12.0.2000
begin
insert into #summary values ('IsLocalDB', cast (SERVERPROPERTY('IsLocalDB') as nvarchar(max)))
insert into #summary values ('IsXTPSupported', cast (SERVERPROPERTY('IsXTPSupported') as nvarchar(max)))
end
RAISERROR ('--ServerProperty--', 0, 1) WITH NOWAIT
select * from #summary
order by PropertyName
drop table #summary
print ''
GO
--changing xp_instance_regenumvalues to dmv access as a part of issue #149
declare @startup table (ArgsName nvarchar(10), ArgsValue nvarchar(max))
insert into @startup
SELECT sReg.value_name, CAST(sReg.value_data AS nvarchar(max))
FROM sys.dm_server_registry AS sReg
WHERE sReg.value_name LIKE N'SQLArg%';
RAISERROR ('--Startup Parameters--', 0, 1) WITH NOWAIT
select * from @startup
go
print ''
create table #traceflg (TraceFlag int, Status int, Global int, Session int)
insert into #traceflg exec ('dbcc tracestatus (-1)')
print ''
RAISERROR ('--traceflags--', 0, 1) WITH NOWAIT
select * from #traceflg
drop table #traceflg
go
print ''
RAISERROR ('--sys.dm_os_schedulers--', 0, 1) WITH NOWAIT
select * from sys.dm_os_schedulers
go
IF (@@MICROSOFTVERSION >= 167773760 --10.0.1600
and @@MICROSOFTVERSION < 171048960) --10.50.0.0
begin
print ''
RAISERROR ('--sys.dm_os_nodes--', 0, 1) WITH NOWAIT
exec sp_executesql N'select node_id, memory_object_address, memory_clerk_address, io_completion_worker_address, memory_node_id, cpu_affinity_mask, online_scheduler_count, idle_scheduler_count active_worker_count, avg_load_balance, timer_task_affinity_mask, permanent_task_affinity_mask, resource_monitor_state, node_state_desc from sys.dm_os_nodes'
end
go
IF (@@MICROSOFTVERSION >= 171048960) --10.50.0.0
begin
print ''
RAISERROR ('--sys.dm_os_nodes--', 0, 1) WITH NOWAIT
exec sp_executesql N'select node_id, memory_object_address, memory_clerk_address, io_completion_worker_address, memory_node_id, cpu_affinity_mask, online_scheduler_count, idle_scheduler_count active_worker_count, avg_load_balance, timer_task_affinity_mask, permanent_task_affinity_mask, resource_monitor_state, online_scheduler_mask, processor_group, node_state_desc from sys.dm_os_nodes'
end
go
print ''
RAISERROR ('--dm_os_sys_info--', 0, 1) WITH NOWAIT
select * from sys.dm_os_sys_info
go
if cast (SERVERPROPERTY('IsClustered') as int) = 1
begin
print ''
RAISERROR ('--fn_virtualservernodes--', 0, 1) WITH NOWAIT
SELECT * FROM fn_virtualservernodes()
end
go
print ''
RAISERROR ('--sys.configurations--', 0, 1) WITH NOWAIT
select configuration_id,
convert(int,value) as 'value',
convert(int,value_in_use) as 'value_in_use',
convert(int,minimum) as 'minimum',
convert(int,maximum) as 'maximum',
convert(int,is_dynamic) as 'is_dynamic',
convert(int,is_advanced) as 'is_advanced',
name
from sys.configurations order by name
go
print ''
RAISERROR ('--database files--', 0, 1) WITH NOWAIT
select database_id, [file_id], file_guid, [type], LEFT(type_desc,10) as 'type_desc', data_space_id, [state], LEFT(state_desc,16) as 'state_desc', size, max_size, growth,
is_media_read_only, is_read_only, is_sparse, is_percent_growth, is_name_reserved, create_lsn, drop_lsn, read_only_lsn, read_write_lsn, differential_base_lsn, differential_base_guid,
differential_base_time, redo_start_lsn, redo_start_fork_guid, redo_target_lsn, redo_target_fork_guid, backup_lsn, db_name(database_id) as 'Database_name', name, physical_name
from master.sys.master_files order by database_id, type, file_id
print ''
go
print ''
RAISERROR ('--sys.databases_ex--', 0, 1) WITH NOWAIT
select cast(DATABASEPROPERTYEX (name,'IsAutoCreateStatistics') as int) 'IsAutoCreateStatistics', cast( DATABASEPROPERTYEX (name,'IsAutoUpdateStatistics') as int) 'IsAutoUpdateStatistics', cast (DATABASEPROPERTYEX (name,'IsAutoCreateStatisticsIncremental') as int) 'IsAutoCreateStatisticsIncremental', * from sys.databases
go
print ''
RAISERROR ('-- Windows Group Default Databases other than master --', 0, 1) WITH NOWAIT
select name,default_database_name from sys.server_principals where [type] = 'G' and is_disabled = 0 and default_database_name != 'master'
go
--removed AG related dmvs as a part of issue #162
print '-- sys.change_tracking_databases --'
select * from sys.change_tracking_databases
print ''
print '-- sys.dm_database_encryption_keys --'
select database_id, encryption_state from sys.dm_database_encryption_keys
print ''
go
IF @@MICROSOFTVERSION >= 251658240 --15.0.2000
BEGIN
PRINT '-- sys.dm_tran_persistent_version_store_stats --'
SELECT * FROM sys.dm_tran_persistent_version_store_stats
PRINT ''
END
go
/*
--windows version from @@version
declare @pos int
set @pos = CHARINDEX(N' on ',@@VERSION)
print substring(@@VERSION, @pos + 4, LEN(@@VERSION))
*/
PRINT '-- sys.certificates --'
SELECT
CONVERT(VARCHAR(64),DB_NAME()) AS [database_name],
name,
certificate_id,
principal_id,
pvt_key_encryption_type,
CONVERT(VARCHAR(32), pvt_key_encryption_type_desc) AS pvt_key_encryption_type_desc,
is_active_for_begin_dialog,
CONVERT(VARCHAR(512), issuer_name) AS issuer_name,
cert_serial_number,
sid,
string_sid,
CONVERT(VARCHAR(512),subject) AS subject,
expiry_date,
start_date,
'0x' + CONVERT(VARCHAR(64),thumbprint,2) AS thumbprint,
CONVERT(VARCHAR(256), attested_by) AS attested_by,
pvt_key_last_backup_date
FROM master.sys.certificates
PRINT ''
--this proc is only present in SQL Server 2019 and later but seems not present in early builds
IF OBJECT_ID('sys.sp_certificate_issuers') IS NOT NULL
BEGIN
CREATE TABLE #certificate_issuers(
certificateid INT,
dnsname NVARCHAR(128) )
INSERT INTO #certificate_issuers
EXEC ('exec sys.sp_certificate_issuers')
PRINT '-- sys_sp_certificate_issuers --'
SELECT certificateid, dnsname
FROM #certificate_issuers
DROP TABLE #certificate_issuers
END
PRINT ''
PRINT ''
-- Collect db_log_info to check for VLF issues
--this table to be used by older versions of SQL Server prior to 2016 SP2
CREATE TABLE #dbcc_loginfo_cur_db
(
RecoveryUnitId INT,
FileId INT,
FileSize BIGINT,
StartOffset BIGINT,
FSeqNo BIGINT,
Status INT,
Parity INT,
CreateLSN NVARCHAR(48)
)
--this table contains all the results
CREATE TABLE #loginfo_all_dbs
(
database_id INT,
[database_name] VARCHAR(64),
vlf_count INT,
vlf_avg_size_mb DECIMAL(10,2),
vlf_min_size_mb DECIMAL(10,2),
vlf_max_size_mb DECIMAL(10,2),
vlf_status INT,
vlf_active BIT
)
DECLARE @dbname nvarchar(64), @dbid INT
DECLARE @dbcc_log_info VARCHAR(MAX)
DECLARE @sql_major_version INT
DECLARE @sql_major_build INT
--check the version of current SQL Server (use old style to support older SQL versions)
SELECT @sql_major_version = (CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS VARCHAR(20)), 4) AS INT)),
@sql_major_build = (CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS VARCHAR(20)), 2) AS INT))
DECLARE Database_Cursor CURSOR FOR SELECT database_id, name FROM MASTER.sys.databases
OPEN Database_Cursor;
FETCH NEXT FROM Database_Cursor into @dbid, @dbname;
WHILE @@FETCH_STATUS = 0
BEGIN
SET @dbcc_log_info = 'DBCC LOGINFO (''' + @dbname + ''') WITH NO_INFOMSGS'
IF ((@sql_major_version >= 14) or (@sql_major_version >= 13) and (@sql_major_build >= 5026 ))
BEGIN
INSERT INTO #loginfo_all_dbs(
database_id ,
database_name ,
vlf_count,
vlf_avg_size_mb ,
vlf_min_size_mb,
vlf_max_size_mb,
vlf_status ,
vlf_active)
SELECT
database_id,
@dbname,
count(*) AS vlf_count,
AVG(vlf_size_mb) AS vlf_avg_size_mb,
MIN(vlf_size_mb) AS vlf_min_size_mb,
MAX(vlf_size_mb) AS vlf_max_size_mb,
vlf_status,
vlf_active
FROM sys.dm_db_log_info (db_id(@dbname))
GROUP BY database_id, vlf_status, vlf_active
END
ELSE
--if version is prior to SQL 2016 SP2, use DBCC LOGINFO to get the data
--but insert and format it into a table as if it came from sys.dm_db_log_info
BEGIN
INSERT INTO #dbcc_loginfo_cur_db (
RecoveryUnitId ,
FileId ,
FileSize ,
StartOffset ,
FSeqNo ,
Status ,
Parity ,
CreateLSN)
EXEC(@dbcc_log_info)
INSERT INTO #loginfo_all_dbs(
database_id ,
database_name ,
vlf_count ,
vlf_avg_size_mb ,
vlf_min_size_mb,
vlf_max_size_mb,
vlf_status ,
vlf_active )
--do the formatting to match the sys.dm_db_log_info standard as much as possible
SELECT
@dbid,
@dbname,
COUNT(li.FSeqNo) AS vlf_count,
CONVERT(DECIMAL(10,2),AVG(li.FileSize/1024/1024.0)) AS vlf_avg_size_mb,
CONVERT(DECIMAL(10,2),MIN(li.FileSize/1024/1024.0)) AS vlf_min_size_mb,
CONVERT(DECIMAL(10,2),MAX(li.FileSize/1024/1024.0)) AS vlf_max_size_mb,
li.Status,
CASE WHEN li.Status = 2 THEN 1 ELSE 0 END AS Active
FROM #dbcc_loginfo_cur_db li
GROUP BY Status, CASE WHEN li.Status = 2 THEN 1 ELSE 0 END
--clean up the temp table for next loop
TRUNCATE TABLE #dbcc_loginfo_cur_db
END
FETCH NEXT FROM Database_Cursor into @dbid, @dbname;
END;
CLOSE Database_Cursor;
DEALLOCATE Database_Cursor;
PRINT '-- sys_dm_db_log_info --'
SELECT
database_id ,
database_name ,
vlf_count ,
vlf_avg_size_mb ,
vlf_min_size_mb ,
vlf_max_size_mb ,
vlf_status ,
vlf_active
FROM #loginfo_all_dbs
ORDER BY database_name
DROP TABLE #dbcc_loginfo_cur_db
DROP TABLE #loginfo_all_dbs
PRINT ''

Просмотреть файл

@ -0,0 +1,176 @@
use tempdb
go
IF OBJECT_ID ('dbo.sp_perf_never_ending_query_snapshots','P') IS NOT NULL
DROP PROCEDURE dbo.sp_perf_never_ending_query_snapshots
GO
CREATE PROCEDURE dbo.sp_perf_never_ending_query_snapshots @appname sysname='SqlLogScout'
AS
SET NOCOUNT ON
DECLARE @cpu_threshold_ms int = 60000
BEGIN
DECLARE @msg varchar(100)
IF EXISTS (SELECT * FROM sys.dm_exec_requests req left outer join sys.dm_exec_sessions sess
on req.session_id = sess.session_id
WHERE req.session_id <> @@SPID AND ISNULL (sess.host_name, '') != @appname and sess.is_user_process = 1 AND req.cpu_time > @cpu_threshold_ms)
BEGIN
DECLARE @runtime datetime = GETDATE(), @runtime_utc datetime = GETUTCDATE()
--SET @msg = 'Start time: ' + CONVERT (varchar(30), @runtime, 126)
RAISERROR (@msg, 0, 1) WITH NOWAIT
PRINT ''
RAISERROR ('-- neverending_query --', 0, 1) WITH NOWAIT
--query the DMV in a loop to compare the
SELECT CONVERT (varchar(30), @runtime, 126) as runtime,
CONVERT (varchar(30), @runtime_utc, 126) as runtime_utc,
qp.session_id,
convert(nvarchar(48), qp.physical_operator_name) as physical_operator_name,
qp.row_count,
qp.estimate_row_count,
qp.node_id,
req.cpu_time,
req.total_elapsed_time,
substring
(REPLACE
(REPLACE
(SUBSTRING
(SQLText.text
, (req.statement_start_offset/2) + 1
, (
(CASE statement_END_offset
WHEN -1
THEN DATALENGTH(SQLText.text)
ELSE req.statement_END_offset
END
- req.statement_start_offset)/2) + 1)
, CHAR(10), ' '), CHAR(13), ' '), 1, 512) AS active_statement_text,
qp.rewind_count,
qp.rebind_count,
qp.end_of_scan_count,
replace(replace(substring(ISNULL(SQLText.text, ''),1,150),CHAR(10), ' '),CHAR(13), ' ') as batch_text
FROM sys.dm_exec_query_profiles qp
RIGHT OUTER JOIN sys.dm_exec_requests req
ON qp.session_id = req.session_id
LEFT OUTER JOIN sys.dm_exec_sessions sess
on req.session_id = sess.session_id
LEFT OUTER JOIN sys.dm_exec_connections conn on conn.session_id = req.session_id
OUTER APPLY sys.dm_exec_sql_text (ISNULL (req.sql_handle, conn.most_recent_sql_handle)) as SQLText
WHERE req.session_id <> @@SPID
AND ISNULL (sess.host_name, '') != @appname
AND sess.is_user_process = 1
AND req.cpu_time > @cpu_threshold_ms
ORDER BY qp.session_id, qp.node_id
--this is to prevent massive grants
OPTION (max_grant_percent = 3, MAXDOP 1)
--flush results to client
RAISERROR (' ', 0, 1) WITH NOWAIT
END
END
GO
IF OBJECT_ID ('dbo.sp_Run_NeverEndingQuery_Stats','P') IS NOT NULL
DROP PROCEDURE dbo.sp_Run_NeverEndingQuery_Stats
GO
CREATE PROCEDURE dbo.sp_Run_NeverEndingQuery_Stats
as
SET NOCOUNT ON
PRINT 'starting query never seems to complete perf stats script...'
set language us_english
PRINT '-- script source --'
select 'query never completes stats script' as script_name
PRINT ''
PRINT '-- script and environment details --'
PRINT 'name value'
PRINT '------------------------ ---------------------------------------------------'
PRINT 'sql server name ' + @@servername
PRINT 'machine name ' + convert (varchar, serverproperty ('machinename'))
PRINT 'sql version (sp) ' + convert (varchar, serverproperty ('productversion')) + ' (' + convert (varchar, serverproperty ('productlevel')) + ')'
PRINT 'edition ' + convert (varchar, serverproperty ('edition'))
PRINT 'script name Query Never Completes stats script'
PRINT 'script file name $file: QueryNeverCompletes_perfstats.sql $'
PRINT 'last modified $date: 2021/09/07 $'
PRINT 'script begin time ' + convert (varchar(30), getdate(), 126)
PRINT 'current database ' + db_name()
PRINT '@@spid ' + ltrim(str(@@spid))
--handle SQL Server 2008 code line, thus need to parse ProductVersion
DECLARE @servermajorversion int
SET @servermajorversion = CONVERT (INT, (REPLACE (LEFT (CONVERT (nvarchar, SERVERPROPERTY ('ProductVersion')), 2), '.', '')))
if (@servermajorversion < 12)
begin
RAISERROR ('Lightweight Profiling SQL Server version is less than 2014. No additional data can be collected', 0, 1) WITH NOWAIT
PRINT ''
return
end
declare @serverbuild int
SET @serverbuild = CONVERT (int, SERVERPROPERTY ('ProductBuild'))
--minimum build 12.0.5000.0 , see https://docs.microsoft.com/en-us/sql/relational-databases/performance/query-profiling-infrastructure?view=sql-server-ver15
if (@servermajorversion <= 12 and @serverbuild < 5000)
begin
RAISERROR ('Lightweight Profiling Your SQL Sever version does not support collecting real-time perf stats on long-running query', 0, 1) WITH NOWAIT
PRINT ''
end
--13.0.4001.0 (SP1)
else if ((@servermajorversion = '13' and @serverbuild <4001) or (@servermajorversion = 12 and @serverbuild >= 5000))
begin
RAISERROR ('Lightweight Profiling Using Lightweight Profiling Ver1 requires that you enable SET STATISTICS PROFILE ON in the same session where the query runs', 0, 1) WITH NOWAIT
PRINT ''
PRINT 'See https://docs.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-exec-query-profiles-transact-sql#examples for more information'
PRINT ''
end
else if ((@servermajorversion = '13' and @serverbuild >=4001) or @servermajorversion = '14')
begin
RAISERROR ('Lightweight Profiling SQL 2016 SP1+ or 2017. Using Lightweight Profiling Ver2', 0, 1) WITH NOWAIT
PRINT ''
PRINT 'Enabling TF 7412'
IF (OBJECT_ID('tempdb.dbo.original_config_tf_7412')) IS NULL
BEGIN
CREATE TABLE tempdb.dbo.original_config_tf_7412 ([ID] [bigint] IDENTITY(1,1) NOT NULL,[TraceFlag] INT, Status INT, Global INT, Session INT)
END
INSERT INTO tempdb.dbo.original_config_tf_7412 EXEC('DBCC TRACESTATUS (7412)')
IF EXISTS (SELECT 1 FROM tempdb.dbo.original_config_tf_7412 WHERE GLOBAL = 0 AND TraceFlag = 7412) DBCC TRACEON (7412, -1)
WHILE (1=1)
BEGIN
--query the DMV in a loop to compare the
EXEC dbo.sp_perf_never_ending_query_snapshots @appname = 'SqlLogScout'
WAITFOR DELAY '00:00:10'
END
end
else if (@servermajorversion >= '15')
begin
RAISERROR ('Lightweight Profiling SQL 2019. Using Lightweight Profiling Ver3 (enabled by default)', 0, 1) WITH NOWAIT
PRINT ''
WHILE (1=1)
BEGIN
--query the DMV in a loop to compare the
EXEC dbo.sp_perf_never_ending_query_snapshots @appname = 'SqlLogScout'
WAITFOR DELAY '00:00:20'
END
end
go
exec dbo.sp_Run_NeverEndingQuery_Stats

Просмотреть файл

Просмотреть файл

@ -212,6 +212,7 @@ Possible values are:
- IO
- LightPerf
- ProcessMonitor
- NeverEndingQuery
- MenuChoice - this directs SQL LogScout to present an interactive menu with Scenario choices. The option is available in cases where multiple parameters are used with SQL_LogScout.cmd. Combining MenuChoice with another scenario choice, causes SQL LogScout to ignore MenuChoice and pick the selected scenario(s). For more information on what data each scenario collects, see [Scenarios](#scenarios)
- NoBasic - this instructs SQL LogScout to skip the collection of basic logs, when Basic scenario is part of another scenario by default. For example if you use GeneralPerf+NoBasic, only the performance logs will be collected and static logs (Basic) will be skipped. If NoBasic+Basic is specified by mistake, the assumption is you intend to collect data; therefore Basic is enabled and NoBasic flag is disabled. Similarly, if NoBasic+Basic+A_VALID_SCENARIO is selected, again the assumption is that data collection is intended. In this case, Basic is enabled, NoBasic is disabled and A_VALID_SCENARIO will collect Basic logs.
@ -255,6 +256,9 @@ Possible values are:
- Quiet - suppresses possible prompts for data input. Selecting Quiet mode implicitly selects "Y" to all the screens that requires an agreement to proceed.
- Noisy - (default) shows prompts requesting user input where necessary
### DisableCtrlCasInput
Used for internal testing only and changes behavior of cancelling SQL LogScout. Do not use this parameter.
## Graphical User Interface (GUI)
The GUI is a feature added in version 5.0 of SQL LogScout. It allows the user to make many of the selections in a single user interface, if they prefer it over the menu options in command prompt. You can do the following in the GUI:
@ -330,16 +334,20 @@ Collects snapshot or static logs. It captures information on:
- OS disk information
- Running filter drivers
- Event logs (system and application in both .CSV and .TXT formats)
- SQL Server dumps found in the errorlog directory. We collect up to 20 dumps if they were created in the last 2 months and are less than 100 MB in size.
- Memory dump .txt files (most recent 200 files)
- IPConfig, DNSClientInfo, and TCP and UDP endpoints
- SQL Errorlogs
- SQL Agent logs
- SystemHealth XELs
- Polybase logs
- Azure Arc Agent logs (if SQL Server enabled for Azure Arc)
- Azure Arc Agent logs (if SQL Server enabled for Azure Arc). More info available at [Azure Instance Metadata Service](https://learn.microsoft.com/en-us/azure/virtual-machines/instance-metadata-service?tabs=windows)
- [SQL Azure VM Information](https://learn.microsoft.com/azure/virtual-machines/instance-metadata-service?tabs=windows) (if SQL Server is Azure Virtual Machine)
- Performance Monitor counters for SQL Server instance and general OS counters - just a few snapshots for a few seconds.
- [AlwaysOn_health.xel](https://docs.microsoft.com/sql/database-engine/availability-groups/windows/always-on-extended-events#bkmk_alwayson_health)
- [MSSQLSERVER_SQLDIAG.xel](https://docs.microsoft.com/sql/database-engine/availability-groups/windows/always-on-health-diagnostics-log)
- [SQL VSS Writer Log (SQL Server 2019 and later)](https://docs.microsoft.com/sql/relational-databases/backup-restore/sql-server-vss-writer-logging)
- [SQL Assessment API](https://docs.microsoft.com/sql/tools/sql-assessment-api/sql-assessment-api-overview) log
- Environment variables full list
## 1. GeneralPerf scenario
@ -353,7 +361,6 @@ Collects all the Basic scenario logs as well as some long-term, continuous logs
- Query Data Store (QDS) info (if that is active)
- Tempdb contention info from SQL DMVs/system views
- Linked Server metadata (SQL DMVs/system views)
- Service Broker configuration information (SQL DMVs/system views)
*Note:* If you combine GeneralPerf with DetailedPerf scenario, then the GeneralPerf will be disabled and only DetailedPerf will be collected.
@ -377,6 +384,7 @@ Collects all the Basic scenario logs as well as Always On configuration informat
- Basic scenario
- Always On diagnostic info (SQL DMVs/system views)
- [AlwaysOn_health.xel](https://docs.microsoft.com/sql/database-engine/availability-groups/windows/always-on-extended-events#bkmk_alwayson_health)
- Always On [Data Movement Latency Xevent ](https://techcommunity.microsoft.com/t5/sql-server-support/troubleshooting-data-movement-latency-between-synchronous-commit/ba-p/319141) and the AG topology XML file required for [AG latency](https://learn.microsoft.com/archive/blogs/psssql/aglatency-report-tool-introduction) analysis.
- Core Xevents trace (RPC and Batch started and completed, login/logout, errors)
- Performance Monitor counters for SQL Server instance and general OS counters
@ -448,6 +456,27 @@ Collects everything that the GeneralPerf scenario does (includes Basic scenario)
Collects a [Process Monitor](https://docs.microsoft.com/en-us/sysinternals/downloads/procmon) (Procmon) log to help with troubleshooting specific file or registry related issues. This collector requires that you have Procmon downloaded and unzipped in a folder of your choice. SQL LogScout will prompt you to provide the path to that folder. You don't need to wrap the path in quotes even if there are spaces in the path name.
## 14. Service Broker and Database mail
Collect logs to help troubleshoot SQL Service Broker and Database mail scenarios. The scenarion includes the following logs:
- Basic scenario
- Service Broker configuration information (SQL DMVs/system views)
- Performance Monitor counters for SQL Server instance and general OS counters
- Extended events (Xevents) for SQL Server Service Broker
## 15. Never Ending Query
Collect logs to help troubleshoot Never Ending Query scenarios. The scenario includes the following logs:
- Basic scenario
- Never Ending Query Perfstats (SQL DMVs/system views)
- Performance Monitor counters for SQL Server instance and general OS counters
- XML Plans for top 5 High CPU consuming queries
- XML Plans for all Never Ending queries
A never-ending query is considered a query that is driving CPU due to execution for a long time, and not one that is waiting for a long-time. This scenario will consider only queries that have consumed 60 seconds of more of CPU time. For more information, see [Troubleshoot queries that seem to never end in SQL Server](https://learn.microsoft.com/en-us/troubleshoot/sql/database-engine/performance/troubleshoot-never-ending-query)
# Output folders
**Output folder**: All the diagnostic log files are collected in the \output (or \output_ddMMyyhhmmss) folder. These include Perfmon log (.BLG), event logs, system information, extended event (.XEL), etc. By default this folder is created in the same location where SQL LogScout files reside (present directory). However a user can choose to collect data on a different disk volume and folder. This can be done by following the prompt for a non-default drive and directory or by using the CustomOutputPath parameter ([Parameters](#parameters))
@ -504,6 +533,8 @@ Diagnostic data is collected from the SQL instance you selected locally on the m
# Security
## Digitally signed files and hash computed
SQL LogScout is released with digitally-signed Powershell files. For other files, SQL LogScout calculates a SHA512 hash and compares it to the expected value of each file. If the stored hash does not match the calculated hash on disk, then SQL LogScout will not run.
To manually validate script signature, you may execute the following:
@ -548,6 +579,10 @@ SignerCertificate : [Subject]
ABDCA79AF9DD48A0EA702AD45260B3C03093FB4B
```
## Encrypted connection to SQL Server
SQL LogScout negotiates connection encryption with the SQL Server it collects data from. It does so by using "Encrypt=True;TrustServerCertificate=true;" and "sqlcmd -C -N" values.
# Sample output
```bash
@ -642,10 +677,9 @@ Copyright (c) 2021 Microsoft Corporation. All rights reserved.
2021-09-10 11:04:21.313 INFO Executing Collector: HighCPU_perfstats
2021-09-10 11:04:21.364 INFO Executing Collector: SQLServerPerfStats
2021-09-10 11:04:23.441 INFO Executing Collector: SQLServerPerfStatsSnapshotStartup
2021-09-10 11:04:23.492 INFO Executing Collector: Query Store
2021-09-10 11:04:23.492 INFO Executing Collector: QueryStore
2021-09-10 11:04:25.552 INFO Executing Collector: TempDBAnalysis
2021-09-10 11:04:25.601 INFO Executing Collector: linked_server_config
2021-09-10 11:04:25.652 INFO Executing Collector: SSB_diag
2021-09-10 11:04:25.708 INFO Collecting logs for 'AlwaysOn' scenario
2021-09-10 11:04:25.740 INFO Executing Collector: AlwaysOnDiagScript
2021-09-10 11:04:25.788 INFO Executing Collector: Xevent_CoreAddSesion
@ -678,7 +712,7 @@ Copyright (c) 2021 Microsoft Corporation. All rights reserved.
2021-09-10 11:04:47.407 INFO Executing Collector: FLTMC_Filters
2021-09-10 11:04:47.464 INFO Executing Collector: FLTMC_Instances
2021-09-10 11:04:47.533 INFO Executing Collector: SystemInfo_Summary
2021-09-10 11:04:47.618 INFO Executing Collector: MiscPssdiagInfo
2021-09-10 11:04:47.618 INFO Executing Collector: MiscDiagInfo
2021-09-10 11:04:47.681 INFO Executing Collector: SQLErrorLogs_AgentLogs_SystemHealth_MemDumps_FciXel
2021-09-10 11:04:50.501 INFO Executing Collector: PolybaseLogs
2021-09-10 11:04:50.533 INFO Executing Collector: SQLAssessmentAPI

Просмотреть файл

@ -525,6 +525,7 @@ Scenario parameter before it.</p>
<li>IO</li>
<li>LightPerf</li>
<li>ProcessMonitor</li>
<li>NeverEndingQuery</li>
<li>MenuChoice - this directs SQL LogScout to present an interactive
menu with Scenario choices. The option is available in cases where
multiple parameters are used with SQL_LogScout.cmd. Combining MenuChoice
@ -604,6 +605,9 @@ agreement to proceed.</li>
<li>Noisy - (default) shows prompts requesting user input where
necessary</li>
</ul>
<h3 id="disablectrlcasinput">DisableCtrlCasInput</h3>
<p>Used for internal testing only and changes behavior of cancelling SQL
LogScout. Do not use this parameter.</p>
<h2 id="graphical-user-interface-gui">Graphical User Interface
(GUI)</h2>
<p>The GUI is a feature added in version 5.0 of SQL LogScout. It allows
@ -703,16 +707,25 @@ configuration, log info, etc)</li>
<li>Running filter drivers</li>
<li>Event logs (system and application in both .CSV and .TXT
formats)</li>
<li>SQL Server dumps found in the errorlog directory. We collect up to
20 dumps if they were created in the last 2 months and are less than 100
MB in size.</li>
<li>Memory dump .txt files (most recent 200 files)</li>
<li>IPConfig, DNSClientInfo, and TCP and UDP endpoints</li>
<li>SQL Errorlogs</li>
<li>SQL Agent logs</li>
<li>SystemHealth XELs</li>
<li>Polybase logs</li>
<li>Azure Arc Agent logs (if SQL Server enabled for Azure Arc)</li>
<li>Azure Arc Agent logs (if SQL Server enabled for Azure Arc). More
info available at <a
href="https://learn.microsoft.com/en-us/azure/virtual-machines/instance-metadata-service?tabs=windows">Azure
Instance Metadata Service</a></li>
<li><a
href="https://learn.microsoft.com/azure/virtual-machines/instance-metadata-service?tabs=windows">SQL
Azure VM Information</a> (if SQL Server is Azure Virtual Machine)</li>
<li>Performance Monitor counters for SQL Server instance and general OS
counters - just a few snapshots for a few seconds.</li>
<li><a
href="https://docs.microsoft.com/sql/database-engine/availability-groups/windows/always-on-extended-events#bkmk_alwayson_health">AlwaysOn_health.xel</a></li>
<li><a
href="https://docs.microsoft.com/sql/database-engine/availability-groups/windows/always-on-health-diagnostics-log">MSSQLSERVER_SQLDIAG.xel</a></li>
<li><a
href="https://docs.microsoft.com/sql/relational-databases/backup-restore/sql-server-vss-writer-logging">SQL
@ -720,6 +733,7 @@ VSS Writer Log (SQL Server 2019 and later)</a></li>
<li><a
href="https://docs.microsoft.com/sql/tools/sql-assessment-api/sql-assessment-api-overview">SQL
Assessment API</a> log</li>
<li>Environment variables full list</li>
</ul>
<h2 id="generalperf-scenario">1. GeneralPerf scenario</h2>
<p>Collects all the Basic scenario logs as well as some long-term,
@ -737,8 +751,6 @@ queries</li>
<li>Query Data Store (QDS) info (if that is active)</li>
<li>Tempdb contention info from SQL DMVs/system views</li>
<li>Linked Server metadata (SQL DMVs/system views)</li>
<li>Service Broker configuration information (SQL DMVs/system
views)</li>
</ul>
<p><em>Note:</em> If you combine GeneralPerf with DetailedPerf scenario,
then the GeneralPerf will be disabled and only DetailedPerf will be
@ -767,6 +779,8 @@ configuration information from DMVs</p>
<ul>
<li>Basic scenario</li>
<li>Always On diagnostic info (SQL DMVs/system views)</li>
<li><a
href="https://docs.microsoft.com/sql/database-engine/availability-groups/windows/always-on-extended-events#bkmk_alwayson_health">AlwaysOn_health.xel</a></li>
<li>Always On <a
href="https://techcommunity.microsoft.com/t5/sql-server-support/troubleshooting-data-movement-latency-between-synchronous-commit/ba-p/319141">Data
Movement Latency Xevent</a> and the AG topology XML file required for <a
@ -889,6 +903,35 @@ registry related issues. This collector requires that you have Procmon
downloaded and unzipped in a folder of your choice. SQL LogScout will
prompt you to provide the path to that folder. You dont need to wrap
the path in quotes even if there are spaces in the path name.</p>
<h2 id="service-broker-and-database-mail">14. Service Broker and
Database mail</h2>
<p>Collect logs to help troubleshoot SQL Service Broker and Database
mail scenarios. The scenarion includes the following logs:</p>
<ul>
<li>Basic scenario</li>
<li>Service Broker configuration information (SQL DMVs/system
views)</li>
<li>Performance Monitor counters for SQL Server instance and general OS
counters</li>
<li>Extended events (Xevents) for SQL Server Service Broker</li>
</ul>
<h2 id="never-ending-query">15. Never Ending Query</h2>
<p>Collect logs to help troubleshoot Never Ending Query scenarios. The
scenario includes the following logs:</p>
<ul>
<li>Basic scenario</li>
<li>Never Ending Query Perfstats (SQL DMVs/system views)</li>
<li>Performance Monitor counters for SQL Server instance and general OS
counters</li>
<li>XML Plans for top 5 High CPU consuming queries</li>
<li>XML Plans for all Never Ending queries</li>
</ul>
<p>A never-ending query is considered a query that is driving CPU due to
execution for a long time, and not one that is waiting for a long-time.
This scenario will consider only queries that have consumed 60 seconds
of more of CPU time. For more information, see <a
href="https://learn.microsoft.com/en-us/troubleshoot/sql/database-engine/performance/troubleshoot-never-ending-query">Troubleshoot
queries that seem to never end in SQL Server</a></p>
<h1 id="output-folders">Output folders</h1>
<p><strong>Output folder</strong>: All the diagnostic log files are
collected in the (or _ddMMyyhhmmss) folder. These include Perfmon log
@ -1041,6 +1084,8 @@ capture data on remote machines. You are prompted to pick a SQL Server
instance you want to target. The SQL Server-specific data collection
comes from a single instance only.</p>
<h1 id="security">Security</h1>
<h2 id="digitally-signed-files-and-hash-computed">Digitally signed files
and hash computed</h2>
<p>SQL LogScout is released with digitally-signed Powershell files. For
other files, SQL LogScout calculates a SHA512 hash and compares it to
the expected value of each file. If the stored hash does not match the
@ -1085,6 +1130,12 @@ class="sourceCode bash"><code class="sourceCode bash"><span id="cb21-1"><a href=
<span id="cb21-18"><a href="#cb21-18" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb21-19"><a href="#cb21-19" aria-hidden="true" tabindex="-1"></a> <span class="ex">[Thumbprint]</span></span>
<span id="cb21-20"><a href="#cb21-20" aria-hidden="true" tabindex="-1"></a> <span class="ex">ABDCA79AF9DD48A0EA702AD45260B3C03093FB4B</span></span></code></pre></div>
<h2 id="encrypted-connection-to-sql-server">Encrypted connection to SQL
Server</h2>
<p>SQL LogScout negotiates connection encryption with the SQL Server it
collects data from. It does so by using
“Encrypt=True;TrustServerCertificate=true;” and “sqlcmd -C -N”
values.</p>
<h1 id="sample-output">Sample output</h1>
<div class="sourceCode" id="cb22"><pre
class="sourceCode bash"><code class="sourceCode bash"><span id="cb22-1"><a href="#cb22-1" aria-hidden="true" tabindex="-1"></a> <span class="ex">======================================================================================================</span></span>
@ -1178,72 +1229,71 @@ class="sourceCode bash"><code class="sourceCode bash"><span id="cb22-1"><a href=
<span id="cb22-89"><a href="#cb22-89" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:21.313 INFO Executing Collector: HighCPU_perfstats </span>
<span id="cb22-90"><a href="#cb22-90" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:21.364 INFO Executing Collector: SQLServerPerfStats </span>
<span id="cb22-91"><a href="#cb22-91" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:23.441 INFO Executing Collector: SQLServerPerfStatsSnapshotStartup </span>
<span id="cb22-92"><a href="#cb22-92" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:23.492 INFO Executing Collector: Query Store </span>
<span id="cb22-92"><a href="#cb22-92" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:23.492 INFO Executing Collector: QueryStore </span>
<span id="cb22-93"><a href="#cb22-93" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:25.552 INFO Executing Collector: TempDBAnalysis </span>
<span id="cb22-94"><a href="#cb22-94" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:25.601 INFO Executing Collector: linked_server_config </span>
<span id="cb22-95"><a href="#cb22-95" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:25.652 INFO Executing Collector: SSB_diag </span>
<span id="cb22-96"><a href="#cb22-96" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:25.708 INFO Collecting logs for <span class="st">&#39;AlwaysOn&#39;</span> scenario </span>
<span id="cb22-97"><a href="#cb22-97" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:25.740 INFO Executing Collector: AlwaysOnDiagScript </span>
<span id="cb22-98"><a href="#cb22-98" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:25.788 INFO Executing Collector: Xevent_CoreAddSesion </span>
<span id="cb22-99"><a href="#cb22-99" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:25.809 INFO Executing Collector: Xevent_AlwaysOn_Data_Movement </span>
<span id="cb22-100"><a href="#cb22-100" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:27.853 INFO Executing Collector: AlwaysOn_Data_Movement_target </span>
<span id="cb22-101"><a href="#cb22-101" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:27.881 INFO Executing Collector: AlwaysOn_Data_Movement_Start </span>
<span id="cb22-102"><a href="#cb22-102" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:27.922 INFO Executing Collector: AlwaysOnHealthXevent </span>
<span id="cb22-103"><a href="#cb22-103" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:28.007 INFO Collecting logs for <span class="st">&#39;BackupRestore&#39;</span> scenario </span>
<span id="cb22-104"><a href="#cb22-104" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:28.023 INFO Executing Collector: Xevent_BackupRestore_AddSession </span>
<span id="cb22-105"><a href="#cb22-105" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:30.070 INFO Executing Collector: EnableTraceFlag </span>
<span id="cb22-106"><a href="#cb22-106" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:30.088 INFO Executing collector: SetVerboseSQLVSSWriterLog</span>
<span id="cb22-107"><a href="#cb22-107" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:30.159 WARN To enable SQL VSS VERBOSE loggging, the SQL VSS Writer service must be restarted now and when shutting down data collection. This is a very quick process.</span>
<span id="cb22-108"><a href="#cb22-108" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:36.697 INFO Console Input: n </span>
<span id="cb22-109"><a href="#cb22-109" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:36.705 INFO You have chosen not to restart SQLWriter Service. No verbose logging will be collected for SQL VSS Writer <span class="er">(</span><span class="ex">2019</span> or later<span class="kw">)</span></span>
<span id="cb22-110"><a href="#cb22-110" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:36.737 INFO Executing Collector: VSSAdmin_Providers </span>
<span id="cb22-111"><a href="#cb22-111" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:36.778 INFO Executing Collector: VSSAdmin_Shadows </span>
<span id="cb22-112"><a href="#cb22-112" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:37.832 INFO Executing Collector: VSSAdmin_Shadowstorage </span>
<span id="cb22-113"><a href="#cb22-113" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:37.873 INFO Executing Collector: VSSAdmin_Writers </span>
<span id="cb22-114"><a href="#cb22-114" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:37.924 INFO Please type <span class="st">&#39;STOP&#39;</span> to terminate the diagnostics collection when you finished capturing the issue </span>
<span id="cb22-115"><a href="#cb22-115" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:43.012 INFO StopCollection Console input: stop </span>
<span id="cb22-116"><a href="#cb22-116" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:43.014 INFO Shutting down the collector </span>
<span id="cb22-117"><a href="#cb22-117" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:43.032 INFO Executing shutdown command: Xevents_Stop </span>
<span id="cb22-118"><a href="#cb22-118" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:43.073 INFO Executing shutdown command: Xevents_Alwayson_Data_Movement_Stop </span>
<span id="cb22-119"><a href="#cb22-119" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:43.098 INFO Executing shutdown command: Disable_BackupRestore_Trace_Flags</span>
<span id="cb22-120"><a href="#cb22-120" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:43.145 INFO Executing shutdown command: PerfmonStop </span>
<span id="cb22-121"><a href="#cb22-121" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:46.228 INFO Executing shutdown command: KillActiveLogscoutSessions </span>
<span id="cb22-122"><a href="#cb22-122" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:47.277 INFO Collecting logs for <span class="st">&#39;Basic&#39;</span> scenario </span>
<span id="cb22-123"><a href="#cb22-123" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:47.298 INFO Executing Collector: TaskListVerbose </span>
<span id="cb22-124"><a href="#cb22-124" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:47.339 INFO Executing Collector: TaskListServices </span>
<span id="cb22-125"><a href="#cb22-125" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:47.407 INFO Executing Collector: FLTMC_Filters </span>
<span id="cb22-126"><a href="#cb22-126" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:47.464 INFO Executing Collector: FLTMC_Instances </span>
<span id="cb22-127"><a href="#cb22-127" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:47.533 INFO Executing Collector: SystemInfo_Summary </span>
<span id="cb22-128"><a href="#cb22-128" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:47.618 INFO Executing Collector: MiscPssdiagInfo </span>
<span id="cb22-129"><a href="#cb22-129" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:47.681 INFO Executing Collector: SQLErrorLogs_AgentLogs_SystemHealth_MemDumps_FciXel </span>
<span id="cb22-130"><a href="#cb22-130" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:50.501 INFO Executing Collector: PolybaseLogs </span>
<span id="cb22-131"><a href="#cb22-131" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:50.533 INFO Executing Collector: SQLAssessmentAPI </span>
<span id="cb22-132"><a href="#cb22-132" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:05:09.554 INFO Executing Collector: UserRights </span>
<span id="cb22-133"><a href="#cb22-133" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:05:12.266 INFO Executing Collector: RunningDrivers </span>
<span id="cb22-134"><a href="#cb22-134" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:05:14.217 INFO Executing Collector: PowerPlan </span>
<span id="cb22-135"><a href="#cb22-135" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:05:14.308 INFO Executing Collector: WindowsHotfixes </span>
<span id="cb22-136"><a href="#cb22-136" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:05:16.694 INFO Executing Collector: GetEventLogs </span>
<span id="cb22-137"><a href="#cb22-137" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:05:16.707 INFO Gathering Application EventLog in TXT and CSV format </span>
<span id="cb22-138"><a href="#cb22-138" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:05:23.218 INFO Produced 10000 records in the EventLog </span>
<span id="cb22-139"><a href="#cb22-139" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:05:29.011 INFO Produced 20000 records in the EventLog </span>
<span id="cb22-140"><a href="#cb22-140" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:05:35.914 INFO Produced 30000 records in the EventLog </span>
<span id="cb22-141"><a href="#cb22-141" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:05:41.975 INFO Produced 39129 records in the EventLog </span>
<span id="cb22-142"><a href="#cb22-142" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:05:41.975 INFO Application EventLog in TXT and CSV format completed! </span>
<span id="cb22-143"><a href="#cb22-143" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:05:41.975 INFO Gathering System EventLog in TXT and CSV format </span>
<span id="cb22-144"><a href="#cb22-144" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:05:50.913 INFO Produced 10000 records in the EventLog </span>
<span id="cb22-145"><a href="#cb22-145" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:05:59.494 INFO Produced 20000 records in the EventLog </span>
<span id="cb22-146"><a href="#cb22-146" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:06:04.839 INFO Produced 26007 records in the EventLog </span>
<span id="cb22-147"><a href="#cb22-147" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:06:04.842 INFO System EventLog in TXT and CSV format completed! </span>
<span id="cb22-148"><a href="#cb22-148" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:06:04.879 INFO Executing Collector: PerfStatsSnapshotShutdown</span>
<span id="cb22-149"><a href="#cb22-149" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:06:04.888 INFO Executing collector: GetSQLVSSWriterLog</span>
<span id="cb22-150"><a href="#cb22-150" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:06:04.900 INFO SQLWriter Service has been restarted</span>
<span id="cb22-151"><a href="#cb22-151" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:06:04.917 INFO Waiting 3 seconds to ensure files are written to and closed by any program including anti-virus... </span>
<span id="cb22-152"><a href="#cb22-152" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:06:08.518 INFO Ending data collection </span>
<span id="cb22-153"><a href="#cb22-153" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:06:08.533 WARN Launching cleanup and exit routine... please wait </span>
<span id="cb22-154"><a href="#cb22-154" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:06:13.780 INFO Thank you for using SQL LogScout! </span>
<span id="cb22-155"><a href="#cb22-155" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb22-156"><a href="#cb22-156" aria-hidden="true" tabindex="-1"></a><span class="ex">Checking</span> for console execution errors logged into .<span class="dt">\#</span>#STDERR.LOG...</span>
<span id="cb22-157"><a href="#cb22-157" aria-hidden="true" tabindex="-1"></a><span class="ex">Removed</span> .<span class="dt">\#</span>#STDERR.LOG which was 0 bytes</span></code></pre></div>
<span id="cb22-95"><a href="#cb22-95" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:25.708 INFO Collecting logs for <span class="st">&#39;AlwaysOn&#39;</span> scenario </span>
<span id="cb22-96"><a href="#cb22-96" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:25.740 INFO Executing Collector: AlwaysOnDiagScript </span>
<span id="cb22-97"><a href="#cb22-97" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:25.788 INFO Executing Collector: Xevent_CoreAddSesion </span>
<span id="cb22-98"><a href="#cb22-98" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:25.809 INFO Executing Collector: Xevent_AlwaysOn_Data_Movement </span>
<span id="cb22-99"><a href="#cb22-99" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:27.853 INFO Executing Collector: AlwaysOn_Data_Movement_target </span>
<span id="cb22-100"><a href="#cb22-100" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:27.881 INFO Executing Collector: AlwaysOn_Data_Movement_Start </span>
<span id="cb22-101"><a href="#cb22-101" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:27.922 INFO Executing Collector: AlwaysOnHealthXevent </span>
<span id="cb22-102"><a href="#cb22-102" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:28.007 INFO Collecting logs for <span class="st">&#39;BackupRestore&#39;</span> scenario </span>
<span id="cb22-103"><a href="#cb22-103" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:28.023 INFO Executing Collector: Xevent_BackupRestore_AddSession </span>
<span id="cb22-104"><a href="#cb22-104" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:30.070 INFO Executing Collector: EnableTraceFlag </span>
<span id="cb22-105"><a href="#cb22-105" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:30.088 INFO Executing collector: SetVerboseSQLVSSWriterLog</span>
<span id="cb22-106"><a href="#cb22-106" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:30.159 WARN To enable SQL VSS VERBOSE loggging, the SQL VSS Writer service must be restarted now and when shutting down data collection. This is a very quick process.</span>
<span id="cb22-107"><a href="#cb22-107" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:36.697 INFO Console Input: n </span>
<span id="cb22-108"><a href="#cb22-108" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:36.705 INFO You have chosen not to restart SQLWriter Service. No verbose logging will be collected for SQL VSS Writer <span class="er">(</span><span class="ex">2019</span> or later<span class="kw">)</span></span>
<span id="cb22-109"><a href="#cb22-109" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:36.737 INFO Executing Collector: VSSAdmin_Providers </span>
<span id="cb22-110"><a href="#cb22-110" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:36.778 INFO Executing Collector: VSSAdmin_Shadows </span>
<span id="cb22-111"><a href="#cb22-111" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:37.832 INFO Executing Collector: VSSAdmin_Shadowstorage </span>
<span id="cb22-112"><a href="#cb22-112" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:37.873 INFO Executing Collector: VSSAdmin_Writers </span>
<span id="cb22-113"><a href="#cb22-113" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:37.924 INFO Please type <span class="st">&#39;STOP&#39;</span> to terminate the diagnostics collection when you finished capturing the issue </span>
<span id="cb22-114"><a href="#cb22-114" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:43.012 INFO StopCollection Console input: stop </span>
<span id="cb22-115"><a href="#cb22-115" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:43.014 INFO Shutting down the collector </span>
<span id="cb22-116"><a href="#cb22-116" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:43.032 INFO Executing shutdown command: Xevents_Stop </span>
<span id="cb22-117"><a href="#cb22-117" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:43.073 INFO Executing shutdown command: Xevents_Alwayson_Data_Movement_Stop </span>
<span id="cb22-118"><a href="#cb22-118" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:43.098 INFO Executing shutdown command: Disable_BackupRestore_Trace_Flags</span>
<span id="cb22-119"><a href="#cb22-119" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:43.145 INFO Executing shutdown command: PerfmonStop </span>
<span id="cb22-120"><a href="#cb22-120" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:46.228 INFO Executing shutdown command: KillActiveLogscoutSessions </span>
<span id="cb22-121"><a href="#cb22-121" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:47.277 INFO Collecting logs for <span class="st">&#39;Basic&#39;</span> scenario </span>
<span id="cb22-122"><a href="#cb22-122" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:47.298 INFO Executing Collector: TaskListVerbose </span>
<span id="cb22-123"><a href="#cb22-123" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:47.339 INFO Executing Collector: TaskListServices </span>
<span id="cb22-124"><a href="#cb22-124" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:47.407 INFO Executing Collector: FLTMC_Filters </span>
<span id="cb22-125"><a href="#cb22-125" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:47.464 INFO Executing Collector: FLTMC_Instances </span>
<span id="cb22-126"><a href="#cb22-126" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:47.533 INFO Executing Collector: SystemInfo_Summary </span>
<span id="cb22-127"><a href="#cb22-127" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:47.618 INFO Executing Collector: MiscDiagInfo </span>
<span id="cb22-128"><a href="#cb22-128" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:47.681 INFO Executing Collector: SQLErrorLogs_AgentLogs_SystemHealth_MemDumps_FciXel </span>
<span id="cb22-129"><a href="#cb22-129" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:50.501 INFO Executing Collector: PolybaseLogs </span>
<span id="cb22-130"><a href="#cb22-130" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:04:50.533 INFO Executing Collector: SQLAssessmentAPI </span>
<span id="cb22-131"><a href="#cb22-131" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:05:09.554 INFO Executing Collector: UserRights </span>
<span id="cb22-132"><a href="#cb22-132" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:05:12.266 INFO Executing Collector: RunningDrivers </span>
<span id="cb22-133"><a href="#cb22-133" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:05:14.217 INFO Executing Collector: PowerPlan </span>
<span id="cb22-134"><a href="#cb22-134" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:05:14.308 INFO Executing Collector: WindowsHotfixes </span>
<span id="cb22-135"><a href="#cb22-135" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:05:16.694 INFO Executing Collector: GetEventLogs </span>
<span id="cb22-136"><a href="#cb22-136" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:05:16.707 INFO Gathering Application EventLog in TXT and CSV format </span>
<span id="cb22-137"><a href="#cb22-137" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:05:23.218 INFO Produced 10000 records in the EventLog </span>
<span id="cb22-138"><a href="#cb22-138" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:05:29.011 INFO Produced 20000 records in the EventLog </span>
<span id="cb22-139"><a href="#cb22-139" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:05:35.914 INFO Produced 30000 records in the EventLog </span>
<span id="cb22-140"><a href="#cb22-140" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:05:41.975 INFO Produced 39129 records in the EventLog </span>
<span id="cb22-141"><a href="#cb22-141" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:05:41.975 INFO Application EventLog in TXT and CSV format completed! </span>
<span id="cb22-142"><a href="#cb22-142" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:05:41.975 INFO Gathering System EventLog in TXT and CSV format </span>
<span id="cb22-143"><a href="#cb22-143" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:05:50.913 INFO Produced 10000 records in the EventLog </span>
<span id="cb22-144"><a href="#cb22-144" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:05:59.494 INFO Produced 20000 records in the EventLog </span>
<span id="cb22-145"><a href="#cb22-145" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:06:04.839 INFO Produced 26007 records in the EventLog </span>
<span id="cb22-146"><a href="#cb22-146" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:06:04.842 INFO System EventLog in TXT and CSV format completed! </span>
<span id="cb22-147"><a href="#cb22-147" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:06:04.879 INFO Executing Collector: PerfStatsSnapshotShutdown</span>
<span id="cb22-148"><a href="#cb22-148" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:06:04.888 INFO Executing collector: GetSQLVSSWriterLog</span>
<span id="cb22-149"><a href="#cb22-149" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:06:04.900 INFO SQLWriter Service has been restarted</span>
<span id="cb22-150"><a href="#cb22-150" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:06:04.917 INFO Waiting 3 seconds to ensure files are written to and closed by any program including anti-virus... </span>
<span id="cb22-151"><a href="#cb22-151" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:06:08.518 INFO Ending data collection </span>
<span id="cb22-152"><a href="#cb22-152" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:06:08.533 WARN Launching cleanup and exit routine... please wait </span>
<span id="cb22-153"><a href="#cb22-153" aria-hidden="true" tabindex="-1"></a><span class="ex">2021-09-10</span> 11:06:13.780 INFO Thank you for using SQL LogScout! </span>
<span id="cb22-154"><a href="#cb22-154" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb22-155"><a href="#cb22-155" aria-hidden="true" tabindex="-1"></a><span class="ex">Checking</span> for console execution errors logged into .<span class="dt">\#</span>#STDERR.LOG...</span>
<span id="cb22-156"><a href="#cb22-156" aria-hidden="true" tabindex="-1"></a><span class="ex">Removed</span> .<span class="dt">\#</span>#STDERR.LOG which was 0 bytes</span></code></pre></div>
<h1 id="test-suite">Test Suite</h1>
<p>The test suite is intended to be used by developers. The set of tests
will grow over time. To run a test, simply execute the

Просмотреть файл

@ -1,860 +0,0 @@
USE tempdb
GO
SET NOCOUNT ON
SET QUOTED_IDENTIFIER ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
SET ARITHABORT ON
SET CONCAT_NULL_YIELDS_NULL ON
SET QUOTED_IDENTIFIER ON
SET NUMERIC_ROUNDABORT OFF
GO
/*******************************************************************
perf stats snapshot
********************************************************************/
use tempdb
go
IF OBJECT_ID ('#sp_perf_stats_snapshot','P') IS NOT NULL
DROP PROCEDURE #sp_perf_stats_snapshot
GO
CREATE PROCEDURE #sp_perf_stats_snapshot
as
begin
PRINT 'Starting SQL Server Perf Stats Snapshot Script...'
PRINT 'SQL Version (SP) ' + CONVERT (varchar, SERVERPROPERTY ('ProductVersion')) + ' (' + CONVERT (varchar, SERVERPROPERTY ('ProductLevel')) + ')'
DECLARE @runtime datetime
DECLARE @cpu_time_start bigint, @cpu_time bigint, @elapsed_time_start bigint, @rowcount bigint
DECLARE @queryduration int, @qrydurationwarnthreshold int
DECLARE @querystarttime datetime
SET @runtime = GETDATE()
SET @qrydurationwarnthreshold = 5000
PRINT ''
PRINT 'Start time: ' + CONVERT (varchar(30), @runtime, 126)
PRINT ''
PRINT '-- Top N Query Plan Statistics --'
SELECT @cpu_time_start = cpu_time FROM sys.dm_exec_sessions WHERE session_id = @@SPID
SET @querystarttime = GETDATE()
SELECT
CONVERT (varchar(30), @runtime, 126) AS 'runtime',
LEFT (p.cacheobjtype + ' (' + p.objtype + ')', 35) AS 'cacheobjtype',
p.usecounts, p.size_in_bytes / 1024 AS 'size_in_kb',
PlanStats.total_worker_time/1000 AS 'tot_cpu_ms', PlanStats.total_elapsed_time/1000 AS 'tot_duration_ms',
PlanStats.total_physical_reads, PlanStats.total_logical_writes, PlanStats.total_logical_reads,
PlanStats.CpuRank, PlanStats.PhysicalReadsRank, PlanStats.DurationRank,
LEFT (CASE
WHEN pa.value=32767 THEN 'ResourceDb'
ELSE ISNULL (DB_NAME (CONVERT (sysname, pa.value)), CONVERT (sysname,pa.value))
END, 40) AS 'dbname',
sql.objectid,
CONVERT (nvarchar(50), CASE
WHEN sql.objectid IS NULL THEN NULL
ELSE REPLACE (REPLACE (sql.[text],CHAR(13), ' '), CHAR(10), ' ')
END) AS 'procname',
REPLACE (REPLACE (SUBSTRING (sql.[text], PlanStats.statement_start_offset/2 + 1,
CASE WHEN PlanStats.statement_end_offset = -1 THEN LEN (CONVERT(nvarchar(max), sql.[text]))
ELSE PlanStats.statement_end_offset/2 - PlanStats.statement_start_offset/2 + 1
END), CHAR(13), ' '), CHAR(10), ' ') AS 'stmt_text'
,PlanStats.query_hash, PlanStats.query_plan_hash, PlanStats.creation_time, PlanStats.statement_start_offset, PlanStats.statement_end_offset, PlanStats.plan_generation_num,
PlanStats.min_worker_time, PlanStats.last_worker_time, PlanStats.max_worker_time,
PlanStats.min_elapsed_time, PlanStats.last_elapsed_time, PlanStats.max_elapsed_time,
PlanStats.min_physical_reads, PlanStats.last_physical_reads, PlanStats.max_physical_reads,
PlanStats.min_logical_writes, PlanStats.last_logical_writes, PlanStats.max_logical_writes,
PlanStats.min_logical_reads, PlanStats.last_logical_reads, PlanStats.max_logical_reads,
PlanStats.plan_handle
FROM
(
SELECT
stat.plan_handle, statement_start_offset, statement_end_offset,
stat.total_worker_time, stat.total_elapsed_time, stat.total_physical_reads,
stat.total_logical_writes, stat.total_logical_reads,
stat.query_hash, stat.query_plan_hash, stat.plan_generation_num, stat.creation_time,
stat.last_worker_time, stat.min_worker_time, stat.max_worker_time, stat.last_elapsed_time, stat.min_elapsed_time, stat.max_elapsed_time,
stat.last_physical_reads, stat.min_physical_reads, stat.max_physical_reads, stat.last_logical_writes, stat.min_logical_writes, stat.max_logical_writes, stat.last_logical_reads, stat.min_logical_reads, stat.max_logical_reads,
ROW_NUMBER() OVER (ORDER BY stat.total_worker_time DESC) AS CpuRank,
ROW_NUMBER() OVER (ORDER BY stat.total_physical_reads DESC) AS PhysicalReadsRank,
ROW_NUMBER() OVER (ORDER BY stat.total_elapsed_time DESC) AS DurationRank
FROM sys.dm_exec_query_stats stat
) AS PlanStats
INNER JOIN sys.dm_exec_cached_plans p ON p.plan_handle = PlanStats.plan_handle
OUTER APPLY sys.dm_exec_plan_attributes (p.plan_handle) pa
OUTER APPLY sys.dm_exec_sql_text (p.plan_handle) AS sql
WHERE (PlanStats.CpuRank < 50 OR PlanStats.PhysicalReadsRank < 50 OR PlanStats.DurationRank < 50)
AND pa.attribute = 'dbid'
ORDER BY tot_cpu_ms DESC
OPTION (MAX_GRANT_PERCENT = 3, MAXDOP 1)
SET @rowcount = @@ROWCOUNT
SET @queryduration = DATEDIFF (ms, @querystarttime, GETDATE())
IF @queryduration > @qrydurationwarnthreshold
BEGIN
SELECT @cpu_time = cpu_time - @cpu_time_start FROM sys.dm_exec_sessions WHERE session_id = @@SPID
PRINT ''
PRINT 'DebugPrint: perfstats_snapshot_querystats - ' + CONVERT (varchar, @queryduration) + 'ms, '
+ CONVERT (varchar, @cpu_time) + 'ms cpu, '
+ 'rowcount=' + CONVERT(varchar, @rowcount)
PRINT ''
END
PRINT ''
PRINT '==============================================================================================='
PRINT 'Missing Indexes: '
PRINT 'The "improvement_measure" column is an indicator of the (estimated) improvement that might '
PRINT 'be seen if the index was created. This is a unitless number, and has meaning only relative '
PRINT 'the same number for other indexes. The measure is a combination of the avg_total_user_cost, '
PRINT 'avg_user_impact, user_seeks, and user_scans columns in sys.dm_db_missing_index_group_stats.'
PRINT ''
PRINT '-- Missing Indexes --'
SELECT CONVERT (varchar(30), @runtime, 126) AS runtime,
mig.index_group_handle, mid.index_handle,
CONVERT (decimal (28,1), migs.avg_total_user_cost * migs.avg_user_impact * (migs.user_seeks + migs.user_scans)) AS improvement_measure,
'CREATE INDEX missing_index_' + CONVERT (varchar, mig.index_group_handle) + '_' + CONVERT (varchar, mid.index_handle)
+ ' ON ' + mid.statement
+ ' (' + ISNULL (mid.equality_columns,'')
+ CASE WHEN mid.equality_columns IS NOT NULL AND mid.inequality_columns IS NOT NULL THEN ',' ELSE '' END + ISNULL (mid.inequality_columns, '')
+ ')'
+ ISNULL (' INCLUDE (' + mid.included_columns + ')', '') AS create_index_statement,
migs.*, mid.database_id, mid.[object_id]
FROM sys.dm_db_missing_index_groups mig
INNER JOIN sys.dm_db_missing_index_group_stats migs ON migs.group_handle = mig.index_group_handle
INNER JOIN sys.dm_db_missing_index_details mid ON mig.index_handle = mid.index_handle
WHERE CONVERT (decimal (28,1), migs.avg_total_user_cost * migs.avg_user_impact * (migs.user_seeks + migs.user_scans)) > 10
ORDER BY migs.avg_total_user_cost * migs.avg_user_impact * (migs.user_seeks + migs.user_scans) DESC
OPTION (MAX_GRANT_PERCENT = 3, MAXDOP 1)
PRINT ''
PRINT ''
PRINT '-- Current database options --'
SELECT LEFT ([name], 128) AS [name],
dbid, cmptlevel,
CONVERT (int, (SELECT SUM (CONVERT (bigint, [size])) * 8192 / 1024 / 1024 FROM master.sys.master_files f WHERE f.database_id = d.dbid)) AS db_size_in_mb,
LEFT (
'Status=' + CONVERT (sysname, DATABASEPROPERTYEX ([name],'Status'))
+ ', Updateability=' + CONVERT (sysname, DATABASEPROPERTYEX ([name],'Updateability'))
+ ', UserAccess=' + CONVERT (varchar(40), DATABASEPROPERTYEX ([name], 'UserAccess'))
+ ', Recovery=' + CONVERT (varchar(40), DATABASEPROPERTYEX ([name], 'Recovery'))
+ ', Version=' + CONVERT (varchar(40), DATABASEPROPERTYEX ([name], 'Version'))
+ CASE WHEN DATABASEPROPERTYEX ([name], 'IsAutoCreateStatistics') = 1 THEN ', IsAutoCreateStatistics' ELSE '' END
+ CASE WHEN DATABASEPROPERTYEX ([name], 'IsAutoUpdateStatistics') = 1 THEN ', IsAutoUpdateStatistics' ELSE '' END
+ CASE WHEN DATABASEPROPERTYEX ([name], 'IsShutdown') = 1 THEN '' ELSE ', Collation=' + CONVERT (varchar(40), DATABASEPROPERTYEX ([name], 'Collation')) END
+ CASE WHEN DATABASEPROPERTYEX ([name], 'IsAutoClose') = 1 THEN ', IsAutoClose' ELSE '' END
+ CASE WHEN DATABASEPROPERTYEX ([name], 'IsAutoShrink') = 1 THEN ', IsAutoShrink' ELSE '' END
+ CASE WHEN DATABASEPROPERTYEX ([name], 'IsInStandby') = 1 THEN ', IsInStandby' ELSE '' END
+ CASE WHEN DATABASEPROPERTYEX ([name], 'IsTornPageDetectionEnabled') = 1 THEN ', IsTornPageDetectionEnabled' ELSE '' END
+ CASE WHEN DATABASEPROPERTYEX ([name], 'IsAnsiNullDefault') = 1 THEN ', IsAnsiNullDefault' ELSE '' END
+ CASE WHEN DATABASEPROPERTYEX ([name], 'IsAnsiNullsEnabled') = 1 THEN ', IsAnsiNullsEnabled' ELSE '' END
+ CASE WHEN DATABASEPROPERTYEX ([name], 'IsAnsiPaddingEnabled') = 1 THEN ', IsAnsiPaddingEnabled' ELSE '' END
+ CASE WHEN DATABASEPROPERTYEX ([name], 'IsAnsiWarningsEnabled') = 1 THEN ', IsAnsiWarningsEnabled' ELSE '' END
+ CASE WHEN DATABASEPROPERTYEX ([name], 'IsArithmeticAbortEnabled') = 1 THEN ', IsArithmeticAbortEnabled' ELSE '' END
+ CASE WHEN DATABASEPROPERTYEX ([name], 'IsCloseCursorsOnCommitEnabled') = 1 THEN ', IsCloseCursorsOnCommitEnabled' ELSE '' END
+ CASE WHEN DATABASEPROPERTYEX ([name], 'IsFullTextEnabled') = 1 THEN ', IsFullTextEnabled' ELSE '' END
+ CASE WHEN DATABASEPROPERTYEX ([name], 'IsLocalCursorsDefault') = 1 THEN ', IsLocalCursorsDefault' ELSE '' END
+ CASE WHEN DATABASEPROPERTYEX ([name], 'IsNumericRoundAbortEnabled') = 1 THEN ', IsNumericRoundAbortEnabled' ELSE '' END
+ CASE WHEN DATABASEPROPERTYEX ([name], 'IsQuotedIdentifiersEnabled') = 1 THEN ', IsQuotedIdentifiersEnabled' ELSE '' END
+ CASE WHEN DATABASEPROPERTYEX ([name], 'IsRecursiveTriggersEnabled') = 1 THEN ', IsRecursiveTriggersEnabled' ELSE '' END
+ CASE WHEN DATABASEPROPERTYEX ([name], 'IsMergePublished') = 1 THEN ', IsMergePublished' ELSE '' END
+ CASE WHEN DATABASEPROPERTYEX ([name], 'IsPublished') = 1 THEN ', IsPublished' ELSE '' END
+ CASE WHEN DATABASEPROPERTYEX ([name], 'IsSubscribed') = 1 THEN ', IsSubscribed' ELSE '' END
+ CASE WHEN DATABASEPROPERTYEX ([name], 'IsSyncWithBackup') = 1 THEN ', IsSyncWithBackup' ELSE '' END
, 512) AS status
FROM master.dbo.sysdatabases d
PRINT ''
print '-- sys.dm_database_encryption_keys TDE --'
declare @sql_major_version INT, @sql_major_build INT, @sql nvarchar (max)
SELECT @sql_major_version = (CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS varchar(20)), 4) AS INT)),
@sql_major_build = (CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS varchar(20)), 2) AS INT))
set @sql = 'select DB_NAME(database_id) as ''database_name'',
[database_id]
,[encryption_state]
,[create_date]
,[regenerate_date]
,[modify_date]
,[set_date]
,[opened_date]
,[key_algorithm]
,[key_length]
,[encryptor_thumbprint]
,[percent_complete]'
IF (@sql_major_version >=11)
BEGIN
set @sql = @sql + ',[encryptor_type]'
END
IF (@sql_major_version >=15)
BEGIN
set @sql = @sql + '[encryption_state_desc]
,[encryption_scan_state]
,[encryption_scan_state_desc]
,[encryption_scan_modify_date]'
END
set @sql = @sql + ' from sys.dm_database_encryption_keys '
--print @sql
exec (@sql)
PRINT ''
print '-- sys.dm_os_loaded_modules --'
select base_address ,
file_version,
product_version,
debug,
patched,
prerelease,
private_build,
special_build,
[language],
company,
[description],
[name]
from sys.dm_os_loaded_modules
PRINT ''
print '-- sys.dm_server_audit_status --'
select
audit_id,
[name],
[status],
status_desc,
status_time,
event_session_address,
audit_file_path,
audit_file_size
from sys.dm_server_audit_status
print ''
print '-- top 10 CPU consuming procedures --'
SELECT TOP 10 getdate() as runtime, d.object_id, d.database_id, db_name(database_id) 'db name', object_name (object_id, database_id) 'proc name', d.cached_time, d.last_execution_time, d.total_elapsed_time, d.total_elapsed_time/d.execution_count AS [avg_elapsed_time], d.last_elapsed_time, d.execution_count
from sys.dm_exec_procedure_stats d
ORDER BY [total_worker_time] DESC
print ''
print '-- top 10 CPU consuming triggers --'
SELECT TOP 10 getdate() as runtime, d.object_id, d.database_id, db_name(database_id) 'db name', object_name (object_id, database_id) 'proc name', d.cached_time, d.last_execution_time, d.total_elapsed_time, d.total_elapsed_time/d.execution_count AS [avg_elapsed_time], d.last_elapsed_time, d.execution_count
from sys.dm_exec_trigger_stats d
ORDER BY [total_worker_time] DESC
print ''
--new stats DMV
set nocount on
declare @dbname sysname, @dbid int
SELECT @sql_major_version = (CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS varchar(20)), 4) AS INT)),
@sql_major_build = (CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS varchar(20)), 2) AS INT))
DECLARE dbCursor CURSOR FOR
select name, database_id from sys.databases where state_desc='ONLINE' and name not in ('model','tempdb') order by name
OPEN dbCursor
FETCH NEXT FROM dbCursor INTO @dbname, @dbid
--replaced sys.dm_db_index_usage_stats by sys.stat since the first doesn't return anything in case the table or index was not accessed since last SQL restart
select @dbid 'Database_Id', @dbname 'Database_Name', Object_name(st.object_id) 'Object_Name', SCHEMA_NAME(schema_id) 'Schema_Name', ss.name 'Statistics_Name',
st.object_id, st.stats_id, st.last_updated, st.rows, st.rows_sampled, st.steps, st.unfiltered_rows, st.modification_counter
into #tmpStats
from sys.stats ss cross apply sys.dm_db_stats_properties (ss.object_id, ss.stats_id) st inner join sys.objects so ON (ss.object_id = so.object_id) where 1=0
--column st.persisted_sample_percent was only introduced on sys.dm_db_stats_properties on SQL Server 2016 (13.x) SP1 CU4 -- 13.0.4446.0 and 2017 CU1 14.0.3006.16
IF (@sql_major_version >14 OR (@sql_major_version=13 AND @sql_major_build>=4446) OR (@sql_major_version=14 AND @sql_major_build>=3006))
BEGIN
ALTER TABLE #tmpStats ADD persisted_sample_percent FLOAT
END
WHILE @@FETCH_STATUS = 0
BEGIN
set @sql = 'USE [' + @dbname + ']'
--replaced sys.dm_db_index_usage_stats by sys.stat since the first doesn't return anything in case the table or index was not accessed since last SQL restart
IF (@sql_major_version >14 OR (@sql_major_version=13 AND @sql_major_build>=4446) OR (@sql_major_version=14 AND @sql_major_build>=3006))
BEGIN
set @sql = @sql + ' insert into #tmpStats select ' + cast( @dbid as nvarchar(20)) + ' ''Database_Id''' + ',''' + @dbname + ''' Database_Name, Object_name(st.object_id) ''Object_Name'', SCHEMA_NAME(schema_id) ''Schema_Name'', ss.name ''Statistics_Name'',
st.object_id, st.stats_id, st.last_updated, st.rows, st.rows_sampled, st.steps, st.unfiltered_rows, st.modification_counter, st.persisted_sample_percent
from sys.stats ss
cross apply sys.dm_db_stats_properties (ss.object_id, ss.stats_id) st
inner join sys.objects so ON (ss.object_id = so.object_id)
where so.type not in (''S'', ''IT'')'
END
ELSE
BEGIN
set @sql = @sql + ' insert into #tmpStats select ' + cast( @dbid as nvarchar(20)) + ' ''Database_Id''' + ',''' + @dbname + ''' Database_Name, Object_name(st.object_id) ''Object_Name'', SCHEMA_NAME(schema_id) ''Schema_Name'', ss.name ''Statistics_Name'',
st.object_id, st.stats_id, st.last_updated, st.rows, st.rows_sampled, st.steps, st.unfiltered_rows, st.modification_counter
from sys.stats ss
cross apply sys.dm_db_stats_properties (ss.object_id, ss.stats_id) st
inner join sys.objects so ON (ss.object_id = so.object_id)
where so.type not in (''S'', ''IT'')'
END
-- added this check to prevent script from failing on principals with restricted access
if HAS_PERMS_BY_NAME(@dbname, 'DATABASE', 'CONNECT') = 1
exec (@sql)
else
PRINT 'Skipped index usage and stats properties check. Principal ' + SUSER_SNAME() + ' does not have CONNECT permission on database ' + @dbname
--print @sql
FETCH NEXT FROM dbCursor INTO @dbname, @dbid
END
close dbCursor
deallocate dbCursor
print ''
print '-- sys.dm_db_stats_properties --'
declare @sql2 nvarchar (max)
IF (@sql_major_version >14 OR (@sql_major_version=13 AND @sql_major_build>=4446) OR (@sql_major_version=14 AND @sql_major_build>=3006))
BEGIN
set @sql2 = 'select --*
Database_Id,
[Database_Name],
[Schema_Name],
[Object_Name],
[object_id],
[stats_id],
[Statistics_Name],
[last_updated],
[rows],
rows_sampled,
steps,
unfiltered_rows,
modification_counter,
persisted_sample_percent
from #tmpStats
order by [database_name]'
END
ELSE
BEGIN
set @sql2 = 'select --*
Database_Id,
[Database_Name],
[Schema_Name],
[Object_Name],
[object_id],
[stats_id],
[Statistics_Name],
[last_updated],
[rows],
rows_sampled,
steps,
unfiltered_rows,
modification_counter
from #tmpStats
order by [database_name]'
END
exec (@sql2)
drop table #tmpStats
print ''
--get disabled indexes
--import in SQLNexus
set nocount on
declare @dbname_index sysname, @dbid_index int
DECLARE dbCursor_Index CURSOR FOR
select QUOTENAME(name) name, database_id from sys.databases where state_desc='ONLINE' and database_id > 4 order by name
OPEN dbCursor_Index
FETCH NEXT FROM dbCursor_Index INTO @dbname_index, @dbid_index
select db_id() 'database_id', db_name() 'database_name', object_name(object_id) 'object_name', object_id,
name,
index_id,
type,
type_desc,
is_disabled into #tblDisabledIndex from sys.indexes where is_disabled = 1 and 1=0
WHILE @@FETCH_STATUS = 0
begin
declare @sql_index nvarchar (max)
set @sql_index = 'USE ' + @dbname_index
set @sql_index = @sql_index + ' insert into #tblDisabledIndex
select db_id() database_id,
db_name() database_name,
object_name(object_id) object_name,
object_id,
name,
index_id,
type,
type_desc,
is_disabled
from sys.indexes where is_disabled = 1'
-- added this check to prevent script from failing on principals with restricted access
if HAS_PERMS_BY_NAME(@dbname_index, 'DATABASE', 'CONNECT') = 1
exec (@sql_index)
else
PRINT 'Skipped disabled indexes check. Principal ' + SUSER_SNAME() + ' does not have CONNECT permission on database ' + @dbname
--print @sql
FETCH NEXT FROM dbCursor_Index INTO @dbname_index, @dbid_index
end
close dbCursor_Index
deallocate dbCursor_Index
print ''
print '--disabled indexes--'
select * from #tblDisabledIndex order by database_name
drop table #tblDisabledIndex
print ''
print '-- server_times --'
select CONVERT (varchar(30), getdate(), 126) as server_time, CONVERT (varchar(30), getutcdate(), 126) utc_time, DATEDIFF(hh, getdate(), getutcdate()) time_delta_hours
/*
this takes too long for large machines
PRINT '-- High Compile Queries --';
WITH XMLNAMESPACES ('http://schemas.microsoft.com/sqlserver/2004/07/showplan' AS sp)
select
stmt.stmt_details.value ('(./sp:QueryPlan/@CompileTime)[1]', 'int') 'CompileTime',
stmt.stmt_details.value ('(./sp:QueryPlan/@CompileCPU)[1]', 'int') 'CompileCPU',
SUBSTRING(replace(replace(stmt.stmt_details.value ('@StatementText', 'nvarchar(max)'), char(13), ' '), char(10), ' '), 1, 8000) 'Statement'
from ( SELECT query_plan as sqlplan FROM sys.dm_exec_cached_plans AS qs CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle))
as p cross apply sqlplan.nodes('//sp:StmtSimple') as stmt (stmt_details)
order by 1 desc;
*/
RAISERROR ('', 0, 1) WITH NOWAIT;
end
go
IF OBJECT_ID ('#sp_perf_stats_snapshot9','P') IS NOT NULL
DROP PROCEDURE #sp_perf_stats_snapshot9
GO
CREATE PROCEDURE #sp_perf_stats_snapshot9
as
begin
exec #sp_perf_stats_snapshot
end
go
IF OBJECT_ID ('#sp_perf_stats_snapshot10','P') IS NOT NULL
DROP PROCEDURE #sp_perf_stats_snapshot10
GO
CREATE PROCEDURE #sp_perf_stats_snapshot10
as
begin
exec #sp_perf_stats_snapshot9
print 'getting resource governor info'
print '=========================================='
print ''
print '-- sys.resource_governor_configuration --'
declare @sql_major_version INT, @sql_major_build INT, @sql nvarchar (max)
SELECT @sql_major_version = (CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS varchar(20)), 4) AS INT)),
@sql_major_build = (CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS varchar(20)), 2) AS INT))
BEGIN
SET @sql = 'select --*
classifier_function_id,
is_enabled'
IF (@sql_major_version >12)
BEGIN
SET @sql = @sql + ',[max_outstanding_io_per_volume]'
END
SET @sql = @sql + ' from sys.resource_governor_configuration;'
--print @sql
exec (@sql)
END
print ''
print '-- sys.resource_governor_resource_pools --'
SET @sql ='select --*
pool_id,
[name],
min_cpu_percent,
max_cpu_percent,
min_memory_percent,
max_memory_percent'
IF (@sql_major_version >=11)
BEGIN
SET @sql = @sql + ',cap_cpu_percent'
END
IF (@sql_major_version >=12)
BEGIN
SET @sql = @sql + ',min_iops_per_volume, max_iops_per_volume'
END
SET @sql = @sql + ' from sys.resource_governor_resource_pools;'
--print @sql
exec (@sql)
print ''
print '-- sys.resource_governor_workload_groups --'
SET @sql ='select --*
group_id,
[name],
importance,
request_max_memory_grant_percent,
request_max_cpu_time_sec,
request_memory_grant_timeout_sec,
max_dop,
group_max_requests,
pool_id'
IF (@sql_major_version >=13)
BEGIN
SET @sql = @sql + ',external_pool_id'
END
SET @sql = @sql + ' from sys.resource_governor_workload_groups'
--print @sql
exec (@sql)
print ''
print 'Query and plan hash capture '
--import in SQLNexus
print '-- top 10 CPU by query_hash --'
select getdate() as runtime, * --into tbl_QueryHashByCPU
from
(
SELECT TOP 10 query_hash, COUNT (distinct query_plan_hash) as 'distinct query_plan_hash count',
sum(execution_count) as 'execution_count',
sum(total_worker_time) as 'total_worker_time',
SUM(total_elapsed_time) as 'total_elapsed_time',
SUM (total_logical_reads) as 'total_logical_reads',
max(REPLACE (REPLACE (SUBSTRING (st.[text], qs.statement_start_offset/2 + 1,
CASE WHEN qs.statement_end_offset = -1 THEN LEN (CONVERT(nvarchar(max), st.[text]))
ELSE qs.statement_end_offset/2 - qs.statement_start_offset/2 + 1
END), CHAR(13), ' '), CHAR(10), ' ')) AS sample_statement_text
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st
group by query_hash
ORDER BY sum(total_worker_time) DESC
) t
OPTION (MAX_GRANT_PERCENT = 3, MAXDOP 1)
print ''
--import in SQLNexus
print '-- top 10 logical reads by query_hash --'
select getdate() as runtime, * --into tbl_QueryHashByLogicalReads
from
(
SELECT TOP 10 query_hash,
COUNT (distinct query_plan_hash) as 'distinct query_plan_hash count',
sum(execution_count) as 'execution_count',
sum(total_worker_time) as 'total_worker_time',
SUM(total_elapsed_time) as 'total_elapsed_time',
SUM (total_logical_reads) as 'total_logical_reads',
max(REPLACE (REPLACE (SUBSTRING (st.[text], qs.statement_start_offset/2 + 1,
CASE WHEN qs.statement_end_offset = -1 THEN LEN (CONVERT(nvarchar(max), st.[text]))
ELSE qs.statement_end_offset/2 - qs.statement_start_offset/2 + 1
END), CHAR(13), ' '), CHAR(10), ' ')) AS sample_statement_text
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st
group by query_hash
ORDER BY sum(total_logical_reads) DESC
) t
OPTION (MAX_GRANT_PERCENT = 3, MAXDOP 1)
print ''
--import in SQLNexus
print '-- top 10 elapsed time by query_hash --'
select getdate() as runtime, * -- into tbl_QueryHashByElapsedTime
from
(
SELECT TOP 10 query_hash,
sum(execution_count) as 'execution_count',
COUNT (distinct query_plan_hash) as 'distinct query_plan_hash count',
sum(total_worker_time) as 'total_worker_time',
SUM(total_elapsed_time) as 'total_elapsed_time',
SUM (total_logical_reads) as 'total_logical_reads',
max(REPLACE (REPLACE (SUBSTRING (st.[text], qs.statement_start_offset/2 + 1,
CASE WHEN qs.statement_end_offset = -1 THEN LEN (CONVERT(nvarchar(max), st.[text]))
ELSE qs.statement_end_offset/2 - qs.statement_start_offset/2 + 1
END), CHAR(13), ' '), CHAR(10), ' ')) AS sample_statement_text
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st
GROUP BY query_hash
ORDER BY sum(total_elapsed_time) DESC
) t
OPTION (MAX_GRANT_PERCENT = 3, MAXDOP 1)
print ''
--import in SQLNexus
print '-- top 10 CPU by query_plan_hash and query_hash --'
SELECT TOP 10 getdate() as runtime, query_plan_hash, query_hash,
COUNT (distinct query_plan_hash) as 'distinct query_plan_hash count',
sum(execution_count) as 'execution_count',
sum(total_worker_time) as 'total_worker_time',
SUM(total_elapsed_time) as 'total_elapsed_time',
SUM (total_logical_reads) as 'total_logical_reads',
max(REPLACE (REPLACE (SUBSTRING (st.[text], qs.statement_start_offset/2 + 1,
CASE WHEN qs.statement_end_offset = -1 THEN LEN (CONVERT(nvarchar(max), st.[text]))
ELSE qs.statement_end_offset/2 - qs.statement_start_offset/2 + 1
END), CHAR(13), ' '), CHAR(10), ' ')) AS sample_statement_text
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st
GROUP BY query_plan_hash, query_hash
ORDER BY sum(total_worker_time) DESC
OPTION (MAX_GRANT_PERCENT = 3, MAXDOP 1)
print ''
--import in SQLNexus
print '-- top 10 logical reads by query_plan_hash and query_hash --'
SELECT TOP 10 getdate() as runtime, query_plan_hash, query_hash, sum(execution_count) as 'execution_count',
sum(total_worker_time) as 'total_worker_time',
SUM(total_elapsed_time) as 'total_elapsed_time',
SUM (total_logical_reads) as 'total_logical_reads',
max(REPLACE (REPLACE (SUBSTRING (st.[text], qs.statement_start_offset/2 + 1,
CASE WHEN qs.statement_end_offset = -1 THEN LEN (CONVERT(nvarchar(max), st.[text]))
ELSE qs.statement_end_offset/2 - qs.statement_start_offset/2 + 1
END), CHAR(13), ' '), CHAR(10), ' ')) AS sample_statement_text
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st
group by query_plan_hash, query_hash
ORDER BY sum(total_logical_reads) DESC
OPTION (MAX_GRANT_PERCENT = 3, MAXDOP 1)
print ''
--import in SQLNexus
print '-- top 10 elapsed time by query_plan_hash and query_hash --'
SELECT TOP 10 getdate() as runtime, query_plan_hash, query_hash, sum(execution_count) as 'execution_count',
sum(total_worker_time) as 'total_worker_time',
SUM(total_elapsed_time) as 'total_elapsed_time',
SUM (total_logical_reads) as 'total_logical_reads',
max(REPLACE (REPLACE (SUBSTRING (st.[text], qs.statement_start_offset/2 + 1,
CASE WHEN qs.statement_end_offset = -1 THEN LEN (CONVERT(nvarchar(max), st.[text]))
ELSE qs.statement_end_offset/2 - qs.statement_start_offset/2 + 1
END), CHAR(13), ' '), CHAR(10), ' ')) AS sample_statement_text
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st
group by query_plan_hash, query_hash
ORDER BY sum(total_elapsed_time) DESC
OPTION (MAX_GRANT_PERCENT = 3, MAXDOP 1)
print ''
end
go
IF OBJECT_ID ('#sp_perf_stats_snapshot11','P') IS NOT NULL
DROP PROCEDURE #sp_perf_stats_snapshot11
GO
CREATE PROCEDURE #sp_perf_stats_snapshot11
as
begin
exec #sp_perf_stats_snapshot10
end
go
IF OBJECT_ID ('#sp_perf_stats_snapshot12','P') IS NOT NULL
DROP PROCEDURE #sp_perf_stats_snapshot12
GO
CREATE PROCEDURE #sp_perf_stats_snapshot12
as
begin
exec #sp_perf_stats_snapshot11
end
go
IF OBJECT_ID ('#sp_perf_stats_snapshot13','P') IS NOT NULL
DROP PROCEDURE #sp_perf_stats_snapshot13
GO
CREATE PROCEDURE #sp_perf_stats_snapshot13
AS
BEGIN
exec #sp_perf_stats_snapshot12
IF OBJECT_ID ('sys.database_scoped_configurations') IS NOT NULL
BEGIN
PRINT '-- sys.database_scoped_configurations --'
DECLARE @database_id INT
DECLARE @dbname SYSNAME
DECLARE @cont INT
DECLARE @maxcont INT
DECLARE @sql_major_version INT
DECLARE @sql_major_build INT
DECLARE @sql nvarchar (max)
DECLARE @is_value_default BIT
DECLARE @dbtable TABLE (
id INT IDENTITY (1,1) PRIMARY KEY,
database_id INT,
dbname SYSNAME
)
SELECT @sql_major_version = (CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS VARCHAR(20)), 4) AS INT)),
@sql_major_build = (CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS VARCHAR(20)), 2) AS INT))
INSERT INTO @dbtable
SELECT database_id, name FROM sys.databases WHERE state_desc='ONLINE' AND name NOT IN ('model','tempdb') ORDER BY name
SET @cont = 1
SET @maxcont = (SELECT MAX(id) FROM @dbtable)
--create the schema
SELECT @database_id as database_id , @dbname as dbname, configuration_id, name, value, value_for_secondary, @is_value_default AS is_value_default
INTO #db_scoped_config
FROM sys.database_scoped_configurations
WHERE 1=0
--insert from all databases
WHILE (@cont<=@maxcont)
BEGIN
SELECT @database_id = database_id,
@dbname = dbname
FROM @dbtable
WHERE id = @cont
SET @sql = 'USE [' + @dbname + ']'
IF (@sql_major_version > 13)
BEGIN
SET @sql = ' INSERT INTO #db_scoped_config SELECT ' + CONVERT(VARCHAR,@database_id) + ',''' + @dbname + ''', configuration_id, name, value, value_for_secondary, is_value_default FROM sys.database_scoped_configurations'
END
ELSE
BEGIN
SET @sql = ' INSERT INTO #db_scoped_config SELECT ' + CONVERT(VARCHAR,@database_id) + ',''' + @dbname + ''', configuration_id, name, value, value_for_secondary, NULL FROM sys.database_scoped_configurations'
END
--PRINT @sql
EXEC (@sql)
SET @cont = @cont + 1
END
SELECT
database_id,
CONVERT(VARCHAR(48), dbname) AS dbname,
configuration_id,
name,
CONVERT(VARCHAR(256), value) AS value,
CONVERT(VARCHAR(256),value_for_secondary) AS value_for_secondary,
is_value_default
FROM #db_scoped_config
PRINT ''
END
END
go
IF OBJECT_ID ('#sp_perf_stats_snapshot14','P') IS NOT NULL
DROP PROCEDURE #sp_perf_stats_snapshot14
GO
CREATE PROCEDURE #sp_perf_stats_snapshot14
as
begin
exec #sp_perf_stats_snapshot13
end
go
IF OBJECT_ID ('#sp_perf_stats_snapshot15','P') IS NOT NULL
DROP PROCEDURE #sp_perf_stats_snapshot15
GO
CREATE PROCEDURE #sp_perf_stats_snapshot15
as
BEGIN
exec #sp_perf_stats_snapshot14
declare @sql_major_version INT
SELECT @sql_major_version = (CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS varchar(20)), 4) AS INT))
-- Check the MS Version
IF (@sql_major_version >=15)
BEGIN
-- Add identifier
print '-- sys.index_resumable_operations --'
SELECT object_id, OBJECT_NAME(object_id) [object_name], index_id, name [index_name],
sql_text,last_max_dop_used, partition_number, state, state_desc, start_time,
last_pause_time, total_execution_time, percent_complete, page_count
FROM sys.index_resumable_operations
PRINT ''
RAISERROR ('', 0, 1) WITH NOWAIT
END
END
GO
IF OBJECT_ID ('#sp_perf_stats_snapshot16','P') IS NOT NULL
DROP PROCEDURE #sp_perf_stats_snapshot16
GO
CREATE PROCEDURE #sp_perf_stats_snapshot16
AS
BEGIN
exec #sp_perf_stats_snapshot15
END
GO
/*****************************************************************
* main loop perf statssnapshot *
******************************************************************/
IF OBJECT_ID ('#sp_Run_PerfStats_Snapshot','P') IS NOT NULL
DROP PROCEDURE #sp_Run_PerfStats_Snapshot
GO
CREATE PROCEDURE #sp_Run_PerfStats_Snapshot @IsLite bit=0
AS
DECLARE @servermajorversion nvarchar(2)
SET @servermajorversion = REPLACE (LEFT (CONVERT (varchar, SERVERPROPERTY ('ProductVersion')), 2), '.', '')
declare @#sp_perf_stats_snapshot_ver sysname
set @#sp_perf_stats_snapshot_ver = '#sp_perf_stats_snapshot' + @servermajorversion
print 'executing procedure ' + @#sp_perf_stats_snapshot_ver
exec @#sp_perf_stats_snapshot_ver
go
exec #sp_Run_PerfStats_Snapshot

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -50,7 +50,7 @@ while(($ProductNumber -ne "1") -and ($ProductNumber -ne "2") -and ($ProductNumbe
Write-Host "4 SSRS (Reporting Services)"
Write-Host "5 SQL Server Agent"
Write-Host ""
$ProductNumber = Read-Host "Enter 1-5>" -CustomLogMessage "Dump Product Console input:"
$ProductNumber = Read-Host "Enter 1-5>" -CustomLogMessage "Dump Product console input:"
if (($ProductNumber -ne "1") -and ($ProductNumber -ne "2") -and ($ProductNumber -ne "3") -and ($ProductNumber -ne "4")-and ($ProductNumber -ne "5"))
{
@ -153,7 +153,7 @@ if (($SqlTaskList.Count -eq 0))
{
Write-LogInformation ""
Write-Host "Please enter the ID for the desired $ProductStr from list above" -ForegroundColor Yellow
$IdStr = Read-Host ">" -CustomLogMessage "ID choice Console input:"
$IdStr = Read-Host ">" -CustomLogMessage "ID choice console input:"
try{
$IdInt = [convert]::ToInt32($IdStr)
@ -182,12 +182,12 @@ if (0 -eq $PIDInt)
# for anything other than SSIS
if (-not ($InstanceOnlyName.StartsWith("MsDtsServer", [System.StringComparison]::CurrentCultureIgnoreCase)))
{
Write-Host "$ProductStr service name = $InstanceOnlyName"
Write-Host "$ProductStr service name = '$InstanceOnlyName'"
$PIDStr = $SqlTaskList | Where-Object {$_.Services -like "*$InstanceOnlyName"} | Select-Object PID
Write-Host "Service ProcessID =" $PIDStr.PID
Write-Host "Service ProcessID = '$($PIDStr.PID)'"
$PIDInt = [convert]::ToInt32($PIDStr.PID)
Write-Host "Using PID=", $PIDInt," for generating a $ProductStr memory dump" -ForegroundColor Green
Write-LogDebug "Using PID = '$PIDInt' for generating a $ProductStr memory dump" -DebugLogLevel 1
Write-Host ""
} else {
@ -217,7 +217,7 @@ if (0 -eq $PIDInt)
{
Write-LogInformation ""
Write-Host "Please enter the ID for the desired SSIS from list above" -ForegroundColor Yellow
$SSISIdStr = Read-Host ">" -CustomLogMessage "ID choice Console input:"
$SSISIdStr = Read-Host ">" -CustomLogMessage "ID choice console input:"
try{
$SSISIdInt = [convert]::ToInt32($SSISIdStr)
@ -268,7 +268,7 @@ if ($ProductNumber -eq "1") #SQL Server memory dump
Write-Host "3 Filtered dump (Not Recommended)"
Write-Host "4 Full dump (Do Not Use on Production systems!)"
Write-Host ""
$SqlDumpTypeSelection = Read-Host "Enter 1-4>" -CustomLogMessage "Dump type Console Input:"
$SqlDumpTypeSelection = Read-Host "Enter 1-4>" -CustomLogMessage "Dump type console input:"
if (($SqlDumpTypeSelection -ne "1") -and ($SqlDumpTypeSelection -ne "2") -And ($SqlDumpTypeSelection -ne "3") -And ($SqlDumpTypeSelection -ne "4" ))
{
@ -291,6 +291,49 @@ if ($ProductNumber -eq "1") #SQL Server memory dump
}
Write-LogDebug "SQL Version: $SqlVersion" -DebugLogLevel 1
[string]$CompressDumpFlag = ""
# if the version is between SQL 2019, CU23 (16000004075) and 16000000000 (SQL 2022)
# or if greater than or equal to 2022 CU8 (16000004075), then we can create a compressed dump -zdmp flag
#if (($SqlDumpTypeSelection -in ("3", "4")) -and ((($SqlVersion -ge 15000004335) -and ($SqlVersion -lt 16000000000)) -or ($SqlVersion -ge 16000004075)) )
if (($SqlDumpTypeSelection -in ("3", "4")) -and (checkSQLVersion -VersionsList @("2022RTMCU8", "2019RTMCU23") -eq $true) )
{
Write-Host "Starting with SQL Server 2019 CU23 and SQL Server 2022 CU8, you can create a compressed full or filter memory dump."
Write-Host "Would you like to create compressed memory dumps?"
while (($isCompressedDump -ne "Y") -and ($isCompressedDump -ne "N"))
{
$isCompressedDump = Read-Host "Create a compressed memory dump? (Y/N)" -CustomLogMessage "Compressed Dump console input:"
$isCompressedDump = $isCompressedDump.ToUpper()
if ($isCompressedDump -eq "Y")
{
$CompressDumpFlag = "-zdmp"
}
elseif ($isCompressedDump -eq "N")
{
$CompressDumpFlag = ""
}
else
{
Write-Host "Not a valid 'Y' or 'N' response"
}
}
}
else {
Write-Host "WARNING: Filtered and Full dumps are not recommended for production systems. They might cause performance issues and should only be used when directed by Microsoft Support." -ForegroundColor Yellow
Write-Host ""
}
}
elseif ($ProductNumber -eq "2") #SSAS dump
{
@ -302,7 +345,7 @@ elseif ($ProductNumber -eq "2") #SSAS dump
Write-Host "1) Mini-dump"
Write-Host "2) Full dump (Do Not Use on Production systems!)" -ForegroundColor Red
Write-Host ""
$SSASDumpTypeSelection = Read-Host "Enter 1-2>" -CustomLogMessage "SSAS Dump Type Console input:"
$SSASDumpTypeSelection = Read-Host "Enter 1-2>" -CustomLogMessage "SSAS Dump Type console input:"
if (($SSASDumpTypeSelection -ne "1") -and ($SSASDumpTypeSelection -ne "2"))
{
@ -334,7 +377,7 @@ elseif ($ProductNumber -eq "3" -or $ProductNumber -eq "4" -or $ProductNumber -eq
Write-Host "1) Mini-dump"
Write-Host "2) Full dump"
Write-Host ""
$SSISDumpTypeSelection = Read-Host "Enter 1-2>" -CustomLogMessage "SSIS Dump Type Console input:"
$SSISDumpTypeSelection = Read-Host "Enter 1-2>" -CustomLogMessage "SSIS Dump Type console input:"
if (($SSISDumpTypeSelection -ne "1") -and ($SSISDumpTypeSelection -ne "2"))
{
@ -363,7 +406,7 @@ while($OutputFolder -eq "" -or !(Test-Path -Path $OutputFolder))
{
Write-Host ""
Write-Host "Where would your like the memory dump stored (output folder)?" -ForegroundColor Yellow
$OutputFolder = Read-Host "Enter an output folder with no quotes (e.g. C:\MyTempFolder or C:\My Folder)" -CustomLogMessage "Dump Output Folder Console Input:"
$OutputFolder = Read-Host "Enter an output folder with no quotes (e.g. C:\MyTempFolder or C:\My Folder)" -CustomLogMessage "Dump Output Folder console input:"
if ($OutputFolder -eq "" -or !(Test-Path -Path $OutputFolder))
{
Write-Host "'" $OutputFolder "' is not a valid folder. Please, enter a valid folder location" -ForegroundColor Yellow
@ -374,11 +417,11 @@ while($OutputFolder -eq "" -or !(Test-Path -Path $OutputFolder))
if ($OutputFolder.Substring($OutputFolder.Length-1) -eq "\")
{
$OutputFolder = $OutputFolder.Substring(0, $OutputFolder.Length-1)
Write-Host "Stripped the last '\' from output folder name. Now folder name is $OutputFolder"
Write-LogDebug "Stripped the last '\' from output folder name. Now folder name is $OutputFolder" -DebugLogLevel 1
}
#find the highest version of SQLDumper.exe on the machine
$NumFolder = dir "c:\Program Files\microsoft sql server\1*" | Select-Object @{name = "DirNameInt"; expression={[int]($_.Name)}}, Name, Mode | Where-Object Mode -Match "da*" | Sort-Object DirNameInt -Descending
$NumFolder = Get-ChildItem -Path "c:\Program Files\microsoft sql server\1*" -Directory | Select-Object @{name = "DirNameInt"; expression={[int]($_.Name)}}, Name, Mode | Sort-Object DirNameInt -Descending
for($j=0;($j -lt $NumFolder.Count); $j++)
{
@ -397,7 +440,7 @@ for($j=0;($j -lt $NumFolder.Count); $j++)
#build the SQLDumper.exe command e.g. (Sqldumper.exe 1096 0 0x0128 0 c:\temp\)
$cmd = "$([char]34)"+$SQLDumperDir + "sqldumper.exe$([char]34)"
$arglist = $PIDInt.ToString() + " 0 " +$DumpType +" 0 $([char]34)" + $OutputFolder + "$([char]34)"
$arglist = $PIDInt.ToString() + " 0 " +$DumpType +" 0 $([char]34)" + $OutputFolder + "$([char]34) " + $CompressDumpFlag
Write-Host "Command for dump generation: ", $cmd, $arglist -ForegroundColor Green
#do-we-want-multiple-dumps section
@ -409,7 +452,7 @@ Write-Host "Would you like to collect multiple memory dumps?" -ForegroundColor Y
$YesNo = $null # reset the variable because it could be assigned at this point
while (($YesNo -ne "y") -and ($YesNo -ne "n"))
{
$YesNo = Read-Host "Enter Y or N>" -CustomLogMessage "Multiple Dumps Choice Console input:"
$YesNo = Read-Host "Enter Y or N>" -CustomLogMessage "Multiple Dumps Choice console input:"
if (($YesNo -eq "y") -or ($YesNo -eq "n") )
{
@ -429,7 +472,7 @@ if ($YesNo -eq "y")
while(1 -ge $DumpCountInt)
{
Write-Host "How many dumps would you like to generate for this $ProductStr" -ForegroundColor Yellow
$DumpCountStr = Read-Host ">" -CustomLogMessage "Dump Count Console input:"
$DumpCountStr = Read-Host ">" -CustomLogMessage "Dump Count console input:"
try
{
@ -451,7 +494,7 @@ if ($YesNo -eq "y")
while(0 -ge $DelayIntervalInt)
{
Write-Host "How frequently (in seconds) would you like to generate the memory dumps?" -ForegroundColor Yellow
$DelayIntervalStr = Read-Host ">" -CustomLogMessage "Dump Frequency Console input:"
$DelayIntervalStr = Read-Host ">" -CustomLogMessage "Dump Frequency console input:"
try
{

Просмотреть файл

@ -62,14 +62,21 @@ param
#specify quiet mode for any Y/N prompts
[Parameter(Position=7,HelpMessage='Choose Quiet|Noisy')]
[string] $InteractivePrompts = "Noisy"
[string] $InteractivePrompts = "Noisy",
#scenario is an optional parameter since there is a menu that covers for it if not present. Always keep as the last parameter
[Parameter(Position=8,Mandatory=$false,HelpMessage='Test parameter that should not be used for most collections')]
[string] $DisableCtrlCasInput = "False"
)
#=======================================Globals =====================================
[console]::TreatControlCAsInput = $true
if ($global:gDisableCtrlCasInput -eq "False")
{
[console]::TreatControlCAsInput = $true
}
[string]$global:present_directory = ""
[string]$global:output_folder = ""
[string]$global:internal_output_folder = ""
@ -97,11 +104,14 @@ param
[int] $global:scenario_bitvalue = 0
[int] $global:sql_major_version = -1
[int] $global:sql_major_build = -1
[long] $global:SQLVERSION = -1
[string] $global:procmon_folder = ""
[bool] $global:gui_mode = $false
[bool] $global:gui_Result = $false
[String[]]$global:varXevents = "xevent_AlwaysOn_Data_Movement", "xevent_core", "xevent_detailed" ,"xevent_general"
[bool] $global:is_secondary_read_intent_only = $false
[bool]$global:allow_static_data_because_service_offline = $false
[string]$global:sql_instance_service_status = ""
#constants
[string] $global:BASIC_NAME = "Basic"
@ -119,30 +129,49 @@ param
[string] $global:LIGHTPERF_NAME = "LightPerf"
[string] $global:NOBASIC_NAME = "NoBasic"
[string] $global:PROCMON_NAME = "ProcessMonitor"
[string] $global:SSB_DBMAIL_NAME = "ServiceBrokerDBMail"
[string] $global:Never_Ending_Query_NAME = "NeverEndingQuery"
[string] $global:DETAILEDPERF_NAME_TEST = "Detailed PERF TEST"
#MenuChoice and NoBasic will not go into this array as they don't need to show up as menu choices
[string[]] $global:ScenarioArray = @($global:BASIC_NAME,$global:GENERALPERF_NAME,$global:DETAILEDPERF_NAME,$global:REPLICATION_NAME,$global:ALWAYSON_NAME,$global:NETWORKTRACE_NAME,$global:MEMORY_NAME,$global:DUMPMEMORY_NAME,$global:WPR_NAME,$global:SETUP_NAME,$global:BACKUPRESTORE_NAME,$global:IO_NAME,$global:LIGHTPERF_NAME,$global:PROCMON_NAME)
[string[]] $global:ScenarioArray = @(
$global:BASIC_NAME,
$global:GENERALPERF_NAME,
$global:DETAILEDPERF_NAME,
$global:REPLICATION_NAME,
$global:ALWAYSON_NAME,
$global:NETWORKTRACE_NAME,
$global:MEMORY_NAME,
$global:DUMPMEMORY_NAME,
$global:WPR_NAME,
$global:SETUP_NAME,
$global:BACKUPRESTORE_NAME,
$global:IO_NAME,
$global:LIGHTPERF_NAME,
$global:PROCMON_NAME,
$global:SSB_DBMAIL_NAME,
$global:Never_Ending_Query_NAME)
# documenting the bits
# 0000000000000001 (1) = Basic
# 0000000000000010 (2) = GeneralPerf
# 0000000000000100 (4) = DetailedPerf
# 0000000000001000 (8) = Replication
# 0000000000010000 (16) = alwayson
# 0000000000100000 (32) = networktrace
# 0000000001000000 (64) = memory
# 0000000010000000 (128) = DumpMemory
# 0000000100000000 (256) = WPR
# 0000001000000000 (512) = Setup
# 0000010000000000 (1024)= BackupRestore
# 0000100000000000 (2048)= IO
# 0001000000000000 (4096)= LightPerf
# 0010000000000000 (8192)= NoBasicBit
# 0100000000000000 (16384)= ProcmonBit
# 1000000000000000 (32768)= futureBit
# 000000000000000001 (1) = Basic
# 000000000000000010 (2) = GeneralPerf
# 000000000000000100 (4) = DetailedPerf
# 000000000000001000 (8) = Replication
# 000000000000010000 (16) = alwayson
# 000000000000100000 (32) = networktrace
# 000000000001000000 (64) = memory
# 000000000010000000 (128) = DumpMemory
# 000000000100000000 (256) = WPR
# 000000001000000000 (512) = Setup
# 000000010000000000 (1024)= BackupRestore
# 000000100000000000 (2048)= IO
# 000001000000000000 (4096)= LightPerf
# 000010000000000000 (8192)= NoBasicBit
# 000100000000000000 (16384)= ProcmonBit
# 001000000000000000 (32768)= ServiceBrokerDBMail
# 010000000000000000 (65536)= neverEndingQuery
# 100000000000000000 (131072) = futureBit
[int] $global:basicBit = 1
[int] $global:generalperfBit = 2
@ -159,7 +188,9 @@ param
[int] $global:LightPerfBit = 4096
[int] $global:NoBasicBit = 8192
[int] $global:ProcmonBit = 16384
[int] $global:futureScBit = 32768
[int] $global:ssbDbmailBit = 32768
[int] $global:neverEndingQBit = 65536
[int] $global:futureScBit = 131072
#globals to map script parameters into
[string[]] $global:gScenario
@ -168,28 +199,32 @@ param
[string] $global:gDiagStartTime
[string] $global:gDiagStopTime
[string] $global:gInteractivePrompts
[string] $global:gDisableCtrlCasInput
$global:ScenarioBitTbl = @{}
$global:ScenarioMenuOrdinals = @{}
#hashtable to use for lookups bits to names and reverse
$global:ScenarioBitTbl.Add($global:BASIC_NAME , $global:basicBit)
$global:ScenarioBitTbl.Add($global:GENERALPERF_NAME , $global:generalperfBit)
$global:ScenarioBitTbl.Add($global:DETAILEDPERF_NAME , $global:detailedperfBit)
$global:ScenarioBitTbl.Add($global:REPLICATION_NAME , $global:replBit)
$global:ScenarioBitTbl.Add($global:ALWAYSON_NAME , $global:alwaysonBit)
$global:ScenarioBitTbl.Add($global:NETWORKTRACE_NAME , $global:networktraceBit)
$global:ScenarioBitTbl.Add($global:MEMORY_NAME , $global:memoryBit)
$global:ScenarioBitTbl.Add($global:DUMPMEMORY_NAME , $global:dumpMemoryBit)
$global:ScenarioBitTbl.Add($global:WPR_NAME , $global:wprBit)
$global:ScenarioBitTbl.Add($global:SETUP_NAME , $global:setupBit)
$global:ScenarioBitTbl.Add($global:BACKUPRESTORE_NAME, $global:BackupRestoreBit)
$global:ScenarioBitTbl.Add($global:IO_NAME , $global:IOBit)
$global:ScenarioBitTbl.Add($global:LIGHTPERF_NAME , $global:LightPerfBit)
$global:ScenarioBitTbl.Add($global:NOBASIC_NAME , $global:NoBasicBit)
$global:ScenarioBitTbl.Add($global:PROCMON_NAME , $global:ProcmonBit)
$global:ScenarioBitTbl.Add("FutureScen" , $global:futureScBit)
$global:ScenarioBitTbl.Add($global:BASIC_NAME , $global:basicBit)
$global:ScenarioBitTbl.Add($global:GENERALPERF_NAME , $global:generalperfBit)
$global:ScenarioBitTbl.Add($global:DETAILEDPERF_NAME , $global:detailedperfBit)
$global:ScenarioBitTbl.Add($global:REPLICATION_NAME , $global:replBit)
$global:ScenarioBitTbl.Add($global:ALWAYSON_NAME , $global:alwaysonBit)
$global:ScenarioBitTbl.Add($global:NETWORKTRACE_NAME , $global:networktraceBit)
$global:ScenarioBitTbl.Add($global:MEMORY_NAME , $global:memoryBit)
$global:ScenarioBitTbl.Add($global:DUMPMEMORY_NAME , $global:dumpMemoryBit)
$global:ScenarioBitTbl.Add($global:WPR_NAME , $global:wprBit)
$global:ScenarioBitTbl.Add($global:SETUP_NAME , $global:setupBit)
$global:ScenarioBitTbl.Add($global:BACKUPRESTORE_NAME , $global:BackupRestoreBit)
$global:ScenarioBitTbl.Add($global:IO_NAME , $global:IOBit)
$global:ScenarioBitTbl.Add($global:LIGHTPERF_NAME , $global:LightPerfBit)
$global:ScenarioBitTbl.Add($global:NOBASIC_NAME , $global:NoBasicBit)
$global:ScenarioBitTbl.Add($global:PROCMON_NAME , $global:ProcmonBit)
$global:ScenarioBitTbl.Add($global:SSB_DBMAIL_NAME , $global:ssbDbmailBit)
$global:ScenarioBitTbl.Add($global:Never_Ending_Query_NAME , $global:neverEndingQBit)
$global:ScenarioBitTbl.Add("FutureScen" , $global:futureScBit)
#hashtable for menu ordinal numbers to be mapped to bits
@ -207,12 +242,21 @@ $global:ScenarioMenuOrdinals.Add(10 , $global:ScenarioBitTbl[$global:BACKUPRESTO
$global:ScenarioMenuOrdinals.Add(11 , $global:ScenarioBitTbl[$global:IO_NAME] )
$global:ScenarioMenuOrdinals.Add(12 , $global:ScenarioBitTbl[$global:LIGHTPERF_NAME] )
$global:ScenarioMenuOrdinals.Add(13 , $global:ScenarioBitTbl[$global:PROCMON_NAME] )
$global:ScenarioMenuOrdinals.Add(14 , $global:ScenarioBitTbl[$global:SSB_DBMAIL_NAME] )
$global:ScenarioMenuOrdinals.Add(15 , $global:ScenarioBitTbl[$global:Never_Ending_Query_NAME] )
# synchronizable hashtable (collection) to be used for thread synchronization
[hashtable] $global:xevent_ht = @{}
$global:xevent_ht.IsSynchronized = $true
#SQLSERVERPROPERTY list will be popluated during intialization
$global:SQLSERVERPROPERTYTBL = @{}
$global:SqlServerVersionsTbl = @{}
#SQLCMD objects reusing the same connection to query SQL Server where needed is more efficient.
[System.Data.SqlClient.SqlConnection] $global:SQLConnection
[System.Data.SqlClient.SqlCommand] $global:SQLCcommand
#=======================================Start of \OUTPUT and \INTERNAL directories and files Section
#======================================== START of Process management section
@ -254,7 +298,8 @@ function PrintHelp ([string]$ValidArguments ="", [int]$index=777, [bool]$brief_h
$delExistingOrCreateNewHlpStr = "`n[-DeleteExistingOrCreateNew <string>] "
$DiagStartTimeHlpStr = "`n[-DiagStartTime <string>] "
$DiagStopTimeHlpStr = "`n[-DiagStopTime <string>] "
$InteractivePromptsHlpStr = "`n[-InteractivePrompts <string>] "
$InteractivePromptsHlpStr = "`n[-InteractivePrompts <string>] "
$DisableCtrlCasInputHlpStr = "`n[-DisableCtrlCasInput <string>] "
@ -268,6 +313,7 @@ function PrintHelp ([string]$ValidArguments ="", [int]$index=777, [bool]$brief_h
5 { $DiagStartTimeHlpStr= $DiagStartTimeHlpStr + "< " + $ValidArguments +" >"}
6 { $DiagStopTimeHlpStr = $DiagStopTimeHlpStr + "< " + $ValidArguments +" >"}
7 { $InteractivePromptsHlpStr = $InteractivePromptsHlpStr + "< " + $ValidArguments +" >"}
8 { $DisableCtrlCasInputHlpStr = $DisableCtrlCasInputHlpStr + "< " + $ValidArguments +" >"}
}
@ -279,7 +325,7 @@ function PrintHelp ([string]$ValidArguments ="", [int]$index=777, [bool]$brief_h
+ $delExistingOrCreateNewHlpStr `
+ $DiagStartTimeHlpStr`
+ $DiagStopTimeHlpStr `
+ $InteractivePromptsHlpStr + "`n" `
+ $InteractivePromptsHlpStr ` + "`n" `
+ "`nExample: `n" `
+ " SQL_LogScout.cmd GeneralPerf+AlwaysOn+BackupRestore DbSrv `"d:\log`" DeleteDefaultFolder `"01-01-2000`" `"04-01-2021 17:00`" Quiet`n"
@ -513,6 +559,20 @@ function ValidateParameters ()
return $false
}
#validate DisableCtrlCasInput parameter
if ($DisableCtrlCasInput -eq "True")
{
#If DisableCtrlCasInput is true, then pass as true
$global:gDisableCtrlCasInput = "True"
}
else
{
#any value other than True or null/whitespace, set value to false.
$global:gDisableCtrlCasInput = "False"
}
# return true since we got to here
return $true
}

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -83,8 +83,38 @@
</Border>
<StackPanel Margin="2.5" Orientation="Horizontal" Grid.Row="1" Grid.ColumnSpan="2" >
<Label Height="25" FontWeight="Bold" HorizontalAlignment="Left" Width="96" >SQL Instance :</Label>
<ComboBox Width="236" Height="23" x:Name="ComboBoxInstanceName"/>
<Label Height="23" FontWeight="Bold" HorizontalAlignment="Left" Width="96" >SQL Instance :</Label>
<ComboBox Width="300" Height="23" x:Name="ComboBoxInstanceName">
<ComboBox.ItemTemplate>
<DataTemplate>
<Border x:Name="border">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<!-- TextBlock for Name -->
<TextBlock Grid.Column="0" Text="{Binding Name}" VerticalAlignment="Center" HorizontalAlignment="Stretch" Foreground="#333333"/>
<!-- TextBlock for DisplayStatus -->
<TextBlock Grid.Column="1" Text="{Binding Status}" VerticalAlignment="Center" HorizontalAlignment="Right" Margin="10 0 0 0" FontStyle="Italic"/>
</Grid>
</Border>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding Status}" Value="Stopped">
<Setter TargetName="border" Property="Width" Value="300"/>
<Setter TargetName="border" Property="Background" Value="#ffe6e6"/>
</DataTrigger>
<DataTrigger Binding="{Binding Status}" Value="Running">
<Setter TargetName="border" Property="Width" Value="300"/>
<Setter TargetName="border" Property="Background" Value="#f2ffe6"/>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</StackPanel>
</Grid>
</Border>
@ -92,7 +122,7 @@
<Border Grid.Row="1" Grid.Column="2" Margin="2" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" BorderBrush="DarkGray" BorderThickness="2" CornerRadius="10" >
<StackPanel Margin="5">
<Label FontWeight="Bold" >Select the SQLVesrion</Label>
<Label FontWeight="Bold" >Select the SQLVersion</Label>
<RadioButton Margin="10,0,0,0">SQL 2008</RadioButton>
<StackPanel Orientation="Horizontal" Margin="2.5"/>
@ -178,8 +208,6 @@
Tempdb contention info from SQL DMVs/system views
<LineBreak />
Linked Server metadata (SQL DMVs/system views)
<LineBreak />
Service Broker configuration information (SQL DMVs/system views)
</TextBlock>
</ToolTip>
@ -354,9 +382,34 @@
</Style>
</CheckBox.Style>
</CheckBox>
<CheckBox x:Name="ServiceBrokerDbMailCheckBox" Margin="20,5,0,0" Content="ServiceBrokerDbMail">
<CheckBox.Style>
<Style TargetType="{x:Type CheckBox}">
<Setter Property="IsChecked" Value="False" />
<Style.Triggers>
<DataTrigger Binding="{Binding XPath=root/Scenario/SsbDbMail/@Value, Source={StaticResource xmlData}}" Value="1">
<Setter Property="IsChecked" Value="True" />
</DataTrigger>
</Style.Triggers>
</Style>
</CheckBox.Style>
</CheckBox>
<CheckBox x:Name="NoBasicCheckBox" VerticalAlignment="Bottom" Margin="20,80,0,0" Content="NoBasic" Height="21">
<CheckBox x:Name="NeverEndingQueryCheckBox" Margin="20,5,0,0" Content="NeverEndingQuery">
<CheckBox.Style>
<Style TargetType="{x:Type CheckBox}">
<Setter Property="IsChecked" Value="False" />
<Style.Triggers>
<DataTrigger Binding="{Binding XPath=root/Scenario/NeverEndingQuery/@Value, Source={StaticResource xmlData}}" Value="1">
<Setter Property="IsChecked" Value="True" />
</DataTrigger>
</Style.Triggers>
</Style>
</CheckBox.Style>
</CheckBox>
<CheckBox x:Name="NoBasicCheckBox" VerticalAlignment="Bottom" Margin="20,40,0,0" Content="NoBasic" Height="21">
<CheckBox.Style>
<Style TargetType="CheckBox">
<Style.Triggers>
@ -494,10 +547,37 @@
</CheckBox.Content>
</CheckBox>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</TreeViewItem>
<TreeViewItem IsEnabled="False" x:Name="TVI_xevent_servicebroker_dbmail">
<TreeViewItem.Header>
<StackPanel Orientation="Horizontal">
<CheckBox x:Name="XeventServiceBrokerDbMail_CheckBox" />
<TextBlock Text="xevent_servicebroker_dbmail" />
</StackPanel>
</TreeViewItem.Header>
<ListView x:Name="list_xevent_servicebroker_dbmail" ItemsSource="{Binding}" Height ="200" Width="200" >
<ListView.ItemTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding State}" Content="{Binding Caption}">
<CheckBox.Style>
<Style TargetType="{x:Type CheckBox}">
<Setter Property="Visibility" Value="Visible"/>
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=Content}" Value="{x:Null}">
<Setter Property="Visibility" Value="Collapsed"/>
</DataTrigger>
</Style.Triggers>
</Style>
</CheckBox.Style>
</CheckBox>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</TreeViewItem>
</TreeView>
</StackPanel>
</TabItem>

Просмотреть файл

@ -23,233 +23,268 @@ IF OBJECT_ID ('sp_mem_stats_grants_mem_script','P') IS NOT NULL
GO
--2017-01-10 changed query text be at statement level
CREATE PROCEDURE sp_mem_stats_grants_mem_script @runtime datetime , @lastruntime datetime =null
as
print '-- query execution memory mem_script--'
SELECT CONVERT (varchar(30), @runtime, 121) as runtime,
r.session_id
, r.blocking_session_id
, r.cpu_time
, r.total_elapsed_time
, r.reads
, r.writes
, r.logical_reads
, r.row_count
, wait_time
, wait_type
, r.command
, ltrim(rtrim(replace(replace (substring (SUBSTRING(q.text,r.statement_start_offset/2 +1, (CASE WHEN r.statement_end_offset = -1 THEN LEN(CONVERT(nvarchar(max), q.text)) * 2 ELSE r.statement_end_offset end - r.statement_start_offset )/2 ) , 1, 1000), char(10), ' '), char(13), ' '))) [text]
--, ltrim(rtrim(replace(replace (substring (q.text, 1, 1000), char(10), ' '), char(13), ' '))) [text]
--, REPLACE (REPLACE (SUBSTRING (q.[text] COLLATE Latin1_General_BIN, CHARINDEX (''CREATE '', SUBSTRING (q.[text] COLLATE Latin1_General_BIN, 1, 1000)), 50), CHAR(10), '' ''), CHAR(13), '' '')
--, q.TEXT --Full SQL Text
, s.login_time
, d.name
, s.login_name
, s.host_name
, s.nt_domain
, s.nt_user_name
, s.status
, c.client_net_address
, s.program_name
, s.client_interface_name
-- , s.total_elapsed_time
, s.last_request_start_time
, s.last_request_end_time
, c.connect_time
, c.last_read
, c.last_write
, mg.dop --Degree of parallelism
, mg.request_time --Date and time when this query requested the memory grant.
, mg.grant_time --NULL means memory has not been granted
, mg.requested_memory_kb
/ 1024 requested_memory_mb --Total requested amount of memory in megabytes
, mg.granted_memory_kb
/ 1024 AS granted_memory_mb --Total amount of memory actually granted in megabytes. NULL if not granted
, mg.required_memory_kb
/ 1024 AS required_memory_mb--Minimum memory required to run this query in megabytes.
, max_used_memory_kb
/ 1024 AS max_used_memory_mb
, mg.query_cost --Estimated query cost.
, mg.timeout_sec --Time-out in seconds before this query gives up the memory grant request.
, mg.resource_semaphore_id --Nonunique ID of the resource semaphore on which this query is waiting.
, mg.wait_time_ms --Wait time in milliseconds. NULL if the memory is already granted.
, CASE mg.is_next_candidate --Is this process the next candidate for a memory grant
WHEN 1 THEN 'Yes'
WHEN 0 THEN 'No'
ELSE 'Memory has been granted'
END AS 'Next Candidate for Memory Grant'
, rs.target_memory_kb
/ 1024 AS server_target_memory_mb --Grant usage target in megabytes.
, rs.max_target_memory_kb
/ 1024 AS server_max_target_memory_mb --Maximum potential target in megabytes. NULL for the small-query resource semaphore.
, rs.total_memory_kb
/ 1024 AS server_total_memory_mb --Memory held by the resource semaphore in megabytes.
, rs.available_memory_kb
/ 1024 AS server_available_memory_mb --Memory available for a new grant in megabytes.
, rs.granted_memory_kb
/ 1024 AS server_granted_memory_mb --Total granted memory in megabytes.
, rs.used_memory_kb
/ 1024 AS server_used_memory_mb --Physically used part of granted memory in megabytes.
, rs.grantee_count --Number of active queries that have their grants satisfied.
, rs.waiter_count --Number of queries waiting for grants to be satisfied.
, rs.timeout_error_count --Total number of time-out errors since server startup. NULL for the small-query resource semaphore.
, rs.forced_grant_count --Total number of forced minimum-memory grants since server startup. NULL for the small-query resource semaphore.
, object_name (q.objectid, q.dbid) 'Object_Name'
FROM sys.dm_exec_requests r
JOIN sys.dm_exec_connections c
ON r.connection_id = c.connection_id
JOIN sys.dm_exec_sessions s
ON c.session_id = s.session_id
JOIN sys.databases d
ON r.database_id = d.database_id
JOIN sys.dm_exec_query_memory_grants mg
ON s.session_id = mg.session_id
INNER JOIN sys.dm_exec_query_resource_semaphores rs
ON mg.resource_semaphore_id = rs.resource_semaphore_id
CROSS APPLY sys.dm_exec_sql_text (r.sql_handle ) AS q
ORDER BY wait_time DESC
OPTION (max_grant_percent = 3, MAXDOP 1)
AS
BEGIN TRY
RAISERROR ('', 0, 1) WITH NOWAIT
go
print '-- query execution memory mem_script--'
SELECT CONVERT (varchar(30), @runtime, 121) as runtime,
r.session_id
, r.blocking_session_id
, r.cpu_time
, r.total_elapsed_time
, r.reads
, r.writes
, r.logical_reads
, r.row_count
, wait_time
, wait_type
, r.command
, ltrim(rtrim(replace(replace (substring (SUBSTRING(q.text,r.statement_start_offset/2 +1, (CASE WHEN r.statement_end_offset = -1 THEN LEN(CONVERT(nvarchar(max), q.text)) * 2 ELSE r.statement_end_offset end - r.statement_start_offset )/2 ) , 1, 1000), char(10), ' '), char(13), ' '))) [text]
--, ltrim(rtrim(replace(replace (substring (q.text, 1, 1000), char(10), ' '), char(13), ' '))) [text]
--, REPLACE (REPLACE (SUBSTRING (q.[text] COLLATE Latin1_General_BIN, CHARINDEX (''CREATE '', SUBSTRING (q.[text] COLLATE Latin1_General_BIN, 1, 1000)), 50), CHAR(10), '' ''), CHAR(13), '' '')
--, q.TEXT --Full SQL Text
, s.login_time
, d.name
, s.login_name
, s.host_name
, s.nt_domain
, s.nt_user_name
, s.status
, c.client_net_address
, s.program_name
, s.client_interface_name
-- , s.total_elapsed_time
, s.last_request_start_time
, s.last_request_end_time
, c.connect_time
, c.last_read
, c.last_write
, mg.dop --Degree of parallelism
, mg.request_time --Date and time when this query requested the memory grant.
, mg.grant_time --NULL means memory has not been granted
, mg.requested_memory_kb
/ 1024 requested_memory_mb --Total requested amount of memory in megabytes
, mg.granted_memory_kb
/ 1024 AS granted_memory_mb --Total amount of memory actually granted in megabytes. NULL if not granted
, mg.required_memory_kb
/ 1024 AS required_memory_mb--Minimum memory required to run this query in megabytes.
, max_used_memory_kb
/ 1024 AS max_used_memory_mb
, mg.query_cost --Estimated query cost.
, mg.timeout_sec --Time-out in seconds before this query gives up the memory grant request.
, mg.resource_semaphore_id --Nonunique ID of the resource semaphore on which this query is waiting.
, mg.wait_time_ms --Wait time in milliseconds. NULL if the memory is already granted.
, CASE mg.is_next_candidate --Is this process the next candidate for a memory grant
WHEN 1 THEN 'Yes'
WHEN 0 THEN 'No'
ELSE 'Memory has been granted'
END AS 'Next Candidate for Memory Grant'
, rs.target_memory_kb
/ 1024 AS server_target_memory_mb --Grant usage target in megabytes.
, rs.max_target_memory_kb
/ 1024 AS server_max_target_memory_mb --Maximum potential target in megabytes. NULL for the small-query resource semaphore.
, rs.total_memory_kb
/ 1024 AS server_total_memory_mb --Memory held by the resource semaphore in megabytes.
, rs.available_memory_kb
/ 1024 AS server_available_memory_mb --Memory available for a new grant in megabytes.
, rs.granted_memory_kb
/ 1024 AS server_granted_memory_mb --Total granted memory in megabytes.
, rs.used_memory_kb
/ 1024 AS server_used_memory_mb --Physically used part of granted memory in megabytes.
, rs.grantee_count --Number of active queries that have their grants satisfied.
, rs.waiter_count --Number of queries waiting for grants to be satisfied.
, rs.timeout_error_count --Total number of time-out errors since server startup. NULL for the small-query resource semaphore.
, rs.forced_grant_count --Total number of forced minimum-memory grants since server startup. NULL for the small-query resource semaphore.
, object_name (q.objectid, q.dbid) 'Object_Name'
FROM sys.dm_exec_requests r
JOIN sys.dm_exec_connections c
ON r.connection_id = c.connection_id
JOIN sys.dm_exec_sessions s
ON c.session_id = s.session_id
JOIN sys.databases d
ON r.database_id = d.database_id
JOIN sys.dm_exec_query_memory_grants mg
ON s.session_id = mg.session_id
INNER JOIN sys.dm_exec_query_resource_semaphores rs
ON mg.resource_semaphore_id = rs.resource_semaphore_id
CROSS APPLY sys.dm_exec_sql_text (r.sql_handle ) AS q
ORDER BY wait_time DESC
OPTION (max_grant_percent = 3, MAXDOP 1)
RAISERROR ('', 0, 1) WITH NOWAIT
END TRY
BEGIN CATCH
PRINT 'Exception occured in: "' + OBJECT_NAME(@@PROCID) + '"'
PRINT 'Msg ' + isnull(cast(Error_Number() as nvarchar(50)), '') + ', Level ' + isnull(cast(Error_Severity() as nvarchar(50)),'') + ', State ' + isnull(cast(Error_State() as nvarchar(50)),'') + ', Server ' + @@servername + ', Line ' + isnull(cast(Error_Line() as nvarchar(50)),'') + char(10) + Error_Message() + char(10);
END CATCH
GO
IF OBJECT_ID ('sp_mem_stats_proccache','P') IS NOT NULL
DROP PROCEDURE sp_mem_stats_proccache
GO
CREATE PROCEDURE sp_mem_stats_proccache @runtime datetime , @lastruntime datetime=null
as
AS
PRINT '-- proccache_summary'
SELECT CONVERT (varchar(30), @runtime, 121) as runtime,
SUM (cast (size_in_bytes as bigint)) AS total_size_in_bytes, COUNT(*) AS plan_count, AVG (usecounts) AS avg_usecounts
FROM sys.dm_exec_cached_plans
RAISERROR ('', 0, 1) WITH NOWAIT
-- This procedure is designed to be run periodically to track the size of the plan cache over time.
BEGIN TRY
PRINT '-- proccache_summary'
SELECT CONVERT (varchar(30), @runtime, 121) as runtime,
-- We have to cast usecounts as bigint to avoid arithmetic overflow in large TB memory sized servers.
SUM (cast (size_in_bytes as bigint)) AS total_size_in_bytes, COUNT(*) AS plan_count, AVG (cast(usecounts as bigint)) AS avg_usecounts
FROM sys.dm_exec_cached_plans
RAISERROR ('', 0, 1) WITH NOWAIT
-- Check for plans that are "polluting" the proc cache with trivial variations
-- (typically due to a lack of parameterization)
PRINT '-- proccache_pollution';
WITH cached_plans (cacheobjtype, objtype, usecounts, size_in_bytes, dbid, objectid, short_qry_text) AS
(
SELECT p.cacheobjtype, p.objtype, p.usecounts, size_in_bytes, s.dbid, s.objectid,
CONVERT (nvarchar(100), REPLACE (REPLACE (
CASE
-- Special cases: handle NULL s.[text] and 'SET NOEXEC'
WHEN s.[text] IS NULL THEN NULL
WHEN CHARINDEX ('noexec', SUBSTRING (s.[text], 1, 200)) > 0 THEN SUBSTRING (s.[text], 1, 40)
-- CASE #1: sp_executesql (query text passed in as 1st parameter)
WHEN (CHARINDEX ('sp_executesql', SUBSTRING (s.[text], 1, 200)) > 0)
THEN SUBSTRING (s.[text], CHARINDEX ('exec', SUBSTRING (s.[text], 1, 200)), 60)
-- CASE #3: any other stored proc -- strip off any parameters
WHEN CHARINDEX ('exec ', SUBSTRING (s.[text], 1, 200)) > 0
THEN SUBSTRING (s.[text], CHARINDEX ('exec', SUBSTRING (s.[text], 1, 4000)),
CHARINDEX (' ', SUBSTRING (SUBSTRING (s.[text], 1, 200) + ' ', CHARINDEX ('exec', SUBSTRING (s.[text], 1, 500)), 200), 9) )
-- CASE #4: stored proc that starts with common prefix 'sp%' instead of 'exec'
WHEN SUBSTRING (s.[text], 1, 2) IN ('sp', 'xp', 'usp')
THEN SUBSTRING (s.[text], 1, CHARINDEX (' ', SUBSTRING (s.[text], 1, 200) + ' '))
-- CASE #5: ad hoc UPD/INS/DEL query (on average, updates/inserts/deletes usually
-- need a shorter substring to avoid hitting parameters)
WHEN SUBSTRING (s.[text], 1, 30) LIKE '%UPDATE %' OR SUBSTRING (s.[text], 1, 30) LIKE '%INSERT %'
OR SUBSTRING (s.[text], 1, 30) LIKE '%DELETE %'
THEN SUBSTRING (s.[text], 1, 30)
-- CASE #6: other ad hoc query
ELSE SUBSTRING (s.[text], 1, 45)
END
, CHAR (10), ' '), CHAR (13), ' ')) AS short_qry_text
FROM sys.dm_exec_cached_plans p
CROSS APPLY sys.dm_exec_sql_text (p.plan_handle) s
)
SELECT CONVERT (varchar(30), @runtime, 121) as runtime,
COUNT(*) AS plan_count, SUM (cast (size_in_bytes as bigint)) AS total_size_in_bytes,
cacheobjtype, objtype, usecounts, dbid, objectid, short_qry_text
FROM cached_plans
GROUP BY cacheobjtype, objtype, usecounts, dbid, objectid, short_qry_text
HAVING COUNT(*) > 100
ORDER BY COUNT(*) DESC
RAISERROR ('', 0, 1) WITH NOWAIT
go
-- Check for plans that are "polluting" the proc cache with trivial variations
-- (typically due to a lack of parameterization)
PRINT '-- proccache_pollution';
WITH cached_plans (cacheobjtype, objtype, usecounts, size_in_bytes, dbid, objectid, short_qry_text) AS
(
SELECT p.cacheobjtype, p.objtype, p.usecounts, size_in_bytes, s.dbid, s.objectid,
CONVERT (nvarchar(100), REPLACE (REPLACE (
CASE
-- Special cases: handle NULL s.[text] and 'SET NOEXEC'
WHEN s.[text] IS NULL THEN NULL
WHEN CHARINDEX ('noexec', SUBSTRING (s.[text], 1, 200)) > 0 THEN SUBSTRING (s.[text], 1, 40)
-- CASE #1: sp_executesql (query text passed in as 1st parameter)
WHEN (CHARINDEX ('sp_executesql', SUBSTRING (s.[text], 1, 200)) > 0)
THEN SUBSTRING (s.[text], CHARINDEX ('exec', SUBSTRING (s.[text], 1, 200)), 60)
-- CASE #3: any other stored proc -- strip off any parameters
WHEN CHARINDEX ('exec ', SUBSTRING (s.[text], 1, 200)) > 0
THEN SUBSTRING (s.[text], CHARINDEX ('exec', SUBSTRING (s.[text], 1, 4000)),
CHARINDEX (' ', SUBSTRING (SUBSTRING (s.[text], 1, 200) + ' ', CHARINDEX ('exec', SUBSTRING (s.[text], 1, 500)), 200), 9) )
-- CASE #4: stored proc that starts with common prefix 'sp%' instead of 'exec'
WHEN SUBSTRING (s.[text], 1, 2) IN ('sp', 'xp', 'usp')
THEN SUBSTRING (s.[text], 1, CHARINDEX (' ', SUBSTRING (s.[text], 1, 200) + ' '))
-- CASE #5: ad hoc UPD/INS/DEL query (on average, updates/inserts/deletes usually
-- need a shorter substring to avoid hitting parameters)
WHEN SUBSTRING (s.[text], 1, 30) LIKE '%UPDATE %' OR SUBSTRING (s.[text], 1, 30) LIKE '%INSERT %'
OR SUBSTRING (s.[text], 1, 30) LIKE '%DELETE %'
THEN SUBSTRING (s.[text], 1, 30)
-- CASE #6: other ad hoc query
ELSE SUBSTRING (s.[text], 1, 45)
END
, CHAR (10), ' '), CHAR (13), ' ')) AS short_qry_text
FROM sys.dm_exec_cached_plans p
CROSS APPLY sys.dm_exec_sql_text (p.plan_handle) s
)
SELECT CONVERT (varchar(30), @runtime, 121) as runtime,
COUNT(*) AS plan_count, SUM (cast (size_in_bytes as bigint)) AS total_size_in_bytes,
cacheobjtype, objtype, usecounts, dbid, objectid, short_qry_text
FROM cached_plans
GROUP BY cacheobjtype, objtype, usecounts, dbid, objectid, short_qry_text
HAVING COUNT(*) > 100
ORDER BY COUNT(*) DESC
RAISERROR ('', 0, 1) WITH NOWAIT
END TRY
BEGIN CATCH
PRINT 'Exception occured in: "' + OBJECT_NAME(@@PROCID) + '"'
PRINT 'Msg ' + isnull(cast(Error_Number() as nvarchar(50)), '') + ', Level ' + isnull(cast(Error_Severity() as nvarchar(50)),'') + ', State ' + isnull(cast(Error_State() as nvarchar(50)),'') + ', Server ' + @@servername + ', Line ' + isnull(cast(Error_Line() as nvarchar(50)),'') + char(10) + Error_Message() + char(10);
END CATCH
GO
IF OBJECT_ID ('sp_mem_stats_general','P') IS NOT NULL
DROP PROCEDURE sp_mem_stats_general
GO
CREATE PROCEDURE sp_mem_stats_general @runtime datetime , @lastruntime datetime=null
as
AS
PRINT '-- dm_os_memory_cache_counters'
SELECT CONVERT (varchar(30), @runtime, 121) as runtime, * FROM sys.dm_os_memory_cache_counters
RAISERROR ('', 0, 1) WITH NOWAIT
-- get the current major build of SQL Server
DECLARE @sql_major_version INT
SELECT @sql_major_version = (CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS varchar(20)), 4) AS INT))
BEGIN TRY
IF OBJECT_ID('tempdb..#db_inmemory') IS NOT NULL
DROP TABLE #db_inmemory;
IF OBJECT_ID('tempdb..#tmp_dm_db_xtp_index_stats ') IS NOT NULL
DROP TABLE #tmp_dm_db_xtp_index_stats ;
IF OBJECT_ID('tempdb..#tmp_dm_db_xtp_hash_index_stats ') IS NOT NULL
DROP TABLE #tmp_dm_db_xtp_hash_index_stats ;
IF OBJECT_ID('tempdb..#tmp_dm_db_xtp_table_memory_stats') IS NOT NULL
DROP TABLE #tmp_dm_db_xtp_table_memory_stats;
IF OBJECT_ID('tempdb..#tmp_dm_db_xtp_memory_consumers') IS NOT NULL
DROP TABLE #tmp_dm_db_xtp_memory_consumers;
PRINT '-- dm_os_memory_cache_counters'
SELECT CONVERT (varchar(30), @runtime, 121) as runtime, * FROM sys.dm_os_memory_cache_counters
RAISERROR ('', 0, 1) WITH NOWAIT
PRINT '-- dm_os_memory_clerks'
SELECT CONVERT (varchar(30), @runtime, 121) as runtime, * FROM sys.dm_os_memory_clerks
RAISERROR ('', 0, 1) WITH NOWAIT
PRINT '-- dm_os_memory_clerks'
SELECT CONVERT (varchar(30), @runtime, 121) as runtime, * FROM sys.dm_os_memory_clerks
RAISERROR ('', 0, 1) WITH NOWAIT
PRINT '-- dm_os_memory_cache_clock_hands'
SELECT CONVERT (varchar(30), @runtime, 121) as runtime, * FROM sys.dm_os_memory_cache_clock_hands
RAISERROR ('', 0, 1) WITH NOWAIT
PRINT '-- dm_os_memory_cache_clock_hands'
SELECT CONVERT (varchar(30), @runtime, 121) as runtime, * FROM sys.dm_os_memory_cache_clock_hands
RAISERROR ('', 0, 1) WITH NOWAIT
PRINT '-- dm_os_memory_cache_hash_tables'
SELECT CONVERT (varchar(30), @runtime, 121) as runtime, * FROM sys.dm_os_memory_cache_hash_tables
RAISERROR ('', 0, 1) WITH NOWAIT
PRINT '-- dm_os_memory_cache_hash_tables'
SELECT CONVERT (varchar(30), @runtime, 121) as runtime, * FROM sys.dm_os_memory_cache_hash_tables
RAISERROR ('', 0, 1) WITH NOWAIT
PRINT '-- dm_os_memory_pools'
SELECT CONVERT (varchar(30), @runtime, 121) as runtime, * FROM sys.dm_os_memory_pools
RAISERROR ('', 0, 1) WITH NOWAIT
PRINT '-- dm_os_memory_pools'
SELECT CONVERT (varchar(30), @runtime, 121) as runtime, * FROM sys.dm_os_memory_pools
RAISERROR ('', 0, 1) WITH NOWAIT
PRINT '-- sys.dm_os_loaded_modules (non-Microsoft)'
SELECT CONVERT (varchar(30), @runtime, 121) as runtime, * FROM sys.dm_os_loaded_modules
WHERE (company NOT LIKE '%Microsoft%' OR company IS NULL)
AND UPPER (name) NOT LIKE '%_NSTAP_.DLL' -- instapi.dll (MS dll), with "i"'s wildcarded for Turkish systems
AND UPPER (name) NOT LIKE '%\ODBC32.DLL' -- ODBC32.dll (MS dll)
RAISERROR ('', 0, 1) WITH NOWAIT
PRINT '-- sys.dm_os_loaded_modules (non-Microsoft)'
SELECT CONVERT (varchar(30), @runtime, 121) as runtime, * FROM sys.dm_os_loaded_modules
WHERE (company NOT LIKE '%Microsoft%' OR company IS NULL)
AND UPPER (name) NOT LIKE '%_NSTAP_.DLL' -- instapi.dll (MS dll), with "i"'s wildcarded for Turkish systems
AND UPPER (name) NOT LIKE '%\ODBC32.DLL' -- ODBC32.dll (MS dll)
RAISERROR ('', 0, 1) WITH NOWAIT
PRINT '-- sys.dm_os_sys_info'
SELECT CONVERT (varchar(30), @runtime, 121) as runtime, *
FROM sys.dm_os_sys_info
RAISERROR ('', 0, 1) WITH NOWAIT
PRINT '-- sys.dm_os_sys_info'
SELECT CONVERT (varchar(30), @runtime, 121) as runtime, *
FROM sys.dm_os_sys_info
RAISERROR ('', 0, 1) WITH NOWAIT
PRINT '-- sys.dm_os_memory_objects (total memory by type, >1MB)'
PRINT '-- sys.dm_os_memory_objects (total memory by type, >1MB)'
declare @sqlmemobj nvarchar(2048)
if @@MICROSOFTVERSION < 184551476 --prior to 2012
begin
set @sqlmemobj =
DECLARE @sqlmemobj NVARCHAR(2048)
IF @sql_major_version < 11 --prior to 2012
BEGIN
SET @sqlmemobj =
'SELECT CONVERT (varchar(30), @runtime, 121) as runtime, ' +
'SUM (CONVERT(bigint, pages_allocated_count) * page_size_in_bytes) AS ''total_bytes_used'', type ' +
'SUM (CONVERT(bigint, (pages_allocated_count * page_size_in_bytes))) AS ''total_bytes_used'', type ' +
'FROM sys.dm_os_memory_objects ' +
'GROUP BY type ' +
'HAVING SUM (CONVERT(bigint,pages_allocated_count) * page_size_in_bytes) >= (1024*1024) ' +
'ORDER BY SUM (CONVERT(bigint,pages_allocated_count) * page_size_in_bytes) DESC '
end
else
begin
set @sqlmemobj =
END
ELSE
BEGIN
SET @sqlmemobj =
'SELECT CONVERT (varchar(30), @runtime, 121) as runtime, ' +
'SUM (CONVERT(bigint, pages_in_bytes)) AS ''total_bytes_used'', type ' +
'FROM sys.dm_os_memory_objects ' +
'GROUP BY type ' +
'HAVING SUM (CONVERT(bigint,pages_in_bytes)) >= (1024*1024) ' +
'ORDER BY SUM (CONVERT(bigint,pages_in_bytes)) DESC '
end
exec sp_executesql @sqlmemobj, N'@runtime datetime', @runtime
END
EXEC SP_EXECUTESQL @sqlmemobj, N'@runtime datetime', @runtime
RAISERROR ('', 0, 1) WITH NOWAIT
-- -- Check for windows memory notifications
PRINT '-- memory_workingset_trimming'
PRINT '-- memory_workingset_trimming'
SELECT
CONVERT (varchar(30), @runtime, 121) as runtime,
DATEADD (ms, a.[Record Time] - sys.ms_ticks, @runtime) AS Notification_time,
@ -257,7 +292,7 @@ DATEADD (ms, a.[Record Time] - sys.ms_ticks, @runtime) AS Notification_time,
sys.ms_ticks AS [Current Time]
FROM
(SELECT x.value('(//Record/ResourceMonitor/Notification)[1]', 'varchar(30)') AS [Notification_type],
x.value('(//Record/MemoryRecord/MemoryUtilization)[1]', 'int') AS [MemoryUtilization %],
x.value('(//Record/MemoryRecord/MemoryUtilization)[1]', 'bigint') AS [MemoryUtilization %],
x.value('(//Record/MemoryRecord/TotalPhysicalMemory)[1]', 'bigint') AS [TotalPhysicalMemory_KB],
x.value('(//Record/MemoryRecord/AvailablePhysicalMemory)[1]', 'bigint') AS [AvailablePhysicalMemory_KB],
x.value('(//Record/MemoryRecord/TotalPageFile)[1]', 'bigint') AS [TotalPageFile_KB],
@ -269,9 +304,9 @@ sys.ms_ticks AS [Current Time]
x.value('(//Record/MemoryNode/CommittedMemory)[1]', 'bigint') AS [SQL_CommittedMemory_KB],
x.value('(//Record/@id)[1]', 'bigint') AS [Record Id],
x.value('(//Record/@type)[1]', 'varchar(30)') AS [Type],
x.value('(//Record/ResourceMonitor/IndicatorsProcess)[1]', 'int') AS [IndicatorsProcess],
x.value('(//Record/ResourceMonitor/IndicatorsSystem)[1]', 'int') AS [IndicatorsSystem],
x.value('(//Record/ResourceMonitor/IndicatorsPool)[1]', 'int') AS [IndicatorsPool],
x.value('(//Record/ResourceMonitor/IndicatorsProcess)[1]', 'bigint') AS [IndicatorsProcess],
x.value('(//Record/ResourceMonitor/IndicatorsSystem)[1]', 'bigint') AS [IndicatorsSystem],
x.value('(//Record/ResourceMonitor/IndicatorsPool)[1]', 'bigint') AS [IndicatorsPool],
x.value('(//Record/@time)[1]', 'bigint') AS [Record Time]
FROM (SELECT CAST (record as xml) FROM sys.dm_os_ring_buffers
WHERE ring_buffer_type = 'RING_BUFFER_RESOURCE_MONITOR') AS R(x)) a
@ -280,8 +315,6 @@ WHERE DATEADD (ms, a.[Record Time] - sys.ms_ticks, @runtime) BETWEEN @lastruntim
ORDER BY DATEADD (ms, a.[Record Time] - sys.ms_ticks, @runtime)
RAISERROR ('', 0, 1) WITH NOWAIT
PRINT '-- sys.dm_os_ring_buffers (RING_BUFFER_RESOURCE_MONITOR and RING_BUFFER_MEMORY_BROKER)'
SELECT CONVERT (varchar(30), @runtime, 121) as runtime,
DATEADD (ms, ring.[timestamp] - sys.ms_ticks, GETDATE()) AS record_time,
@ -292,6 +325,477 @@ WHERE ring.ring_buffer_type IN ( 'RING_BUFFER_RESOURCE_MONITOR' , 'RING_BUFFER_M
AND DATEADD (ms, ring.timestamp - sys.ms_ticks, GETDATE()) BETWEEN @lastruntime AND GETDATE()
RAISERROR ('', 0, 1) WITH NOWAIT
PRINT '-- sys.dm_os_memory_brokers --'
SELECT CONVERT (varchar(30), @runtime, 121) as runtime, *
FROM sys.dm_os_memory_brokers
RAISERROR ('', 0, 1) WITH NOWAIT
--In-Memory OLTP related data
DECLARE @database_id INT
DECLARE @dbname SYSNAME
DECLARE @count INT
DECLARE @maxcount INT
DECLARE @sql NVARCHAR(MAX)
DECLARE @dbtable TABLE (id INT IDENTITY (1,1) PRIMARY KEY,
database_id INT,
dbname SYSNAME
)
IF (@sql_major_version > 11)
BEGIN
--database level in-memory dmvs
SELECT IDENTITY(INT,1,1) AS id,
@database_id as database_id ,
@dbname as dbname
INTO #db_inmemory
FROM sys.databases
WHERE 1=0
INSERT INTO @dbtable
SELECT database_id, name FROM sys.databases WHERE state_desc='ONLINE'
SET @count = 1
SET @maxcount = (SELECT MAX(id) FROM @dbtable)
WHILE (@count<=@maxcount)
BEGIN
SELECT @database_id = database_id,
@dbname = dbname
FROM @dbtable
WHERE id = @count
SET @sql = N'USE [' + @dbname + '];
IF EXISTS(SELECT type_desc FROM sys.data_spaces WHERE type_desc = ''MEMORY_OPTIMIZED_DATA_FILEGROUP'')
BEGIN
INSERT INTO #db_inmemory VALUES (' + CONVERT(NVARCHAR(50),@database_id) + ',''' + @dbname +''');
END'
--print @sql
EXEC (@sql)
SET @count = @count + 1
END
SET @count = 1
SET @maxcount = (SELECT MAX(id) FROM #db_inmemory)
PRINT '-- sys.dm_db_xtp_index_stats --'
CREATE TABLE #tmp_dm_db_xtp_index_stats (
[dbname] SYSNAME NULL,
[object_id] BIGINT NULL,
[xtp_object_id]BIGINT NULL,
[index_name] SYSNAME NULL,
[scans_started]BIGINT NULL,
[scans_retries]BIGINT NULL,
[rows_returned]BIGINT NULL,
[rows_touched]BIGINT NULL,
[rows_expiring]BIGINT NULL,
[rows_expired]BIGINT NULL,
[rows_expired_removed]BIGINT NULL,
[phantom_scans_started]BIGINT NULL,
[phantom_scans_retries]BIGINT NULL,
[phantom_rows_touched]BIGINT NULL,
[phantom_expiring_rows_encountered]BIGINT NULL,
[phantom_expired_removed_rows_encountered]BIGINT NULL,
[phantom_expired_rows_removed]BIGINT NULL,
[object_address]VARBINARY(8) NULL
)
WHILE (@count<=@maxcount)
BEGIN
SELECT @database_id = database_id,
@dbname = dbname
FROM #db_inmemory
WHERE id = @count
IF (@sql_major_version >=13 )
BEGIN
SET @sql = N'USE [' + @dbname + '];
INSERT INTO #tmp_dm_db_xtp_index_stats
SELECT '''+@dbname+''',
[object_id],
[xtp_object_id],
[index_id],
[scans_started],
[scans_retries],
[rows_returned],
[rows_touched],
[rows_expiring],
[rows_expired],
[rows_expired_removed],
[phantom_scans_started],
[phantom_scans_retries],
[phantom_rows_touched],
[phantom_expiring_rows_encountered],
[phantom_expired_removed_rows_encountered],
[phantom_expired_rows_removed],
[object_address]
FROM sys.dm_db_xtp_index_stats ids;'
END
ELSE
BEGIN
SET @sql = N'USE [' + @dbname + '];
INSERT INTO #tmp_dm_db_xtp_index_stats
SELECT '''+@dbname+''',
[object_id],
NULL,--[xtp_object_id],
[index_id],
[scans_started],
[scans_retries],
[rows_returned],
[rows_touched],
[rows_expiring],
[rows_expired],
[rows_expired_removed],
[phantom_scans_started],
[phantom_scans_retries],
[phantom_rows_touched],
[phantom_expiring_rows_encountered],
[phantom_expired_removed_rows_encountered],
[phantom_expired_rows_removed],
[object_address]
FROM sys.dm_db_xtp_index_stats AS ids;'
END
--print @sql
EXEC (@sql)
SET @count = @count + 1
END
SELECT CONVERT (varchar(30), @runtime, 121) as runtime, * FROM #tmp_dm_db_xtp_index_stats
RAISERROR ('', 0, 1) WITH NOWAIT
PRINT '-- sys.dm_db_xtp_hash_index_stats --'
SET @count = 1
SET @maxcount = (SELECT MAX(id) FROM #db_inmemory)
CREATE TABLE #tmp_dm_db_xtp_hash_index_stats(
dbname SYSNAME NULL,
objname SYSNAME NULL,
indexname SYSNAME NULL,
total_bucket_count BIGINT NULL,
empty_bucket_count BIGINT NULL,
empty_bucket_percent FLOAT NULL,
avg_chain_length BIGINT NULL,
max_chain_length BIGINT NULL
)
WHILE (@count<=@maxcount)
BEGIN
SELECT @database_id = database_id,
@dbname = dbname
FROM #db_inmemory
WHERE id = @count
SET @sql = N'USE [' + @dbname + '];
INSERT INTO #tmp_dm_db_xtp_hash_index_stats
SELECT '''+@dbname+''',
OBJECT_NAME(hs.object_id),
i.name,
hs.total_bucket_count,
hs.empty_bucket_count,
FLOOR((CAST(empty_bucket_count as float)/total_bucket_count) * 100),
hs.avg_chain_length,
hs.max_chain_length
FROM sys.dm_db_xtp_hash_index_stats AS hs
INNER JOIN sys.indexes AS i
ON hs.object_id=i.object_id AND hs.index_id=i.index_id'
--print @sql
EXEC (@sql)
SET @count = @count + 1
END
SELECT CONVERT (varchar(30), @runtime, 121) as runtime,* FROM #tmp_dm_db_xtp_hash_index_stats
RAISERROR ('', 0, 1) WITH NOWAIT
PRINT '-- sys.dm_db_xtp_table_memory_stats --'
SET @count = 1
SET @maxcount = (SELECT MAX(id) FROM #db_inmemory)
CREATE TABLE #tmp_dm_db_xtp_table_memory_stats(
[dbname] SYSNAME NULL,
[object_name] SYSNAME NULL,
[object_id] BIGINT NULL,
[memory_allocated_for_table_kb] BIGINT NULL,
[memory_used_by_table_kb] BIGINT NULL,
[memory_allocated_for_indexes_kb] BIGINT NULL,
[memory_used_by_indexes_kb] BIGINT NULL
)
WHILE (@count<=@maxcount)
BEGIN
SELECT @database_id = database_id,
@dbname = dbname
FROM #db_inmemory
WHERE id = @count
SET @sql = N'USE [' + @dbname + '];
INSERT INTO #tmp_dm_db_xtp_table_memory_stats
SELECT '''+@dbname+''',
OBJECT_NAME(object_id),
[object_id],
[memory_allocated_for_table_kb],
[memory_used_by_table_kb],
[memory_allocated_for_indexes_kb],
[memory_used_by_indexes_kb]
FROM sys.dm_db_xtp_table_memory_stats
OPTION (FORCE ORDER);'
--print @sql
EXEC (@sql)
SET @count = @count + 1
END
SELECT CONVERT (varchar(30), @runtime, 121) as runtime,* from #tmp_dm_db_xtp_table_memory_stats
RAISERROR ('', 0, 1) WITH NOWAIT
PRINT '-- sys.dm_db_xtp_memory_consumers --'
SET @count = 1
SET @maxcount = (SELECT MAX(id) FROM #db_inmemory)
CREATE TABLE #tmp_dm_db_xtp_memory_consumers (
[dbname] SYSNAME NULL,
[object_name] SYSNAME NULL,
[memory_consumer_id] BIGINT NULL,
[memory_consumer_type] INT NULL,
[memory_consumer_type_desc]NVARCHAR(64) NULL,
[memory_consumer_desc]NVARCHAR(64) NULL,
[object_id] BIGINT NULL,
[xtp_object_id] BIGINT NULL,
[index_id] INT NULL,
[allocated_bytes] BIGINT NULL,
[used_bytes] BIGINT NULL,
[allocation_count] INT NULL,
[partition_count] INT NULL,
[sizeclass_count] INT NULL,
[min_sizeclass] INT NULL,
[max_sizeclass]INT NULL,
[memory_consumer_address] VARBINARY(8) NULL
)
WHILE (@count<=@maxcount)
BEGIN
SELECT @database_id = database_id,
@dbname = dbname
FROM #db_inmemory
WHERE id = @count
IF (@sql_major_version >=13 )
BEGIN
SET @sql = N'USE [' + @dbname + '];
INSERT INTO #tmp_dm_db_xtp_memory_consumers
SELECT '''+@dbname+''',
CONVERT(char(20), OBJECT_NAME(object_id)) AS Name,
[memory_consumer_id],
[memory_consumer_type],
[memory_consumer_type_desc],
[memory_consumer_desc],
[object_id],
[xtp_object_id],
[index_id],
[allocated_bytes],
[used_bytes],
[allocation_count],
[partition_count],
[sizeclass_count],
[min_sizeclass],
[max_sizeclass],
[memory_consumer_address]
FROM sys.dm_db_xtp_memory_consumers;'
END
ELSE
BEGIN
SET @sql = N'USE [' + @dbname + '];
INSERT INTO #tmp_dm_db_xtp_memory_consumers
SELECT '''+@dbname+''',
CONVERT(char(20), OBJECT_NAME(object_id)) AS Name,
[memory_consumer_id],
[memory_consumer_type],
[memory_consumer_type_desc],
[memory_consumer_desc],
[object_id],
NULL,--[xtp_object_id],
[index_id],
[allocated_bytes],
[used_bytes],
[allocation_count],
[partition_count],
[sizeclass_count],
[min_sizeclass],
[max_sizeclass],
[memory_consumer_address]
FROM sys.dm_db_xtp_memory_consumers;'
END
--print @sql
EXEC (@sql)
SET @count = @count + 1
END
SELECT CONVERT (varchar(30), @runtime, 121) as runtime, * FROM #tmp_dm_db_xtp_memory_consumers
RAISERROR ('', 0, 1) WITH NOWAIT
PRINT '-- sys.dm_db_xtp_object_stats --'
SET @count = 1
SET @maxcount = (SELECT MAX(id) FROM #db_inmemory)
CREATE table #tmp_dm_db_xtp_object_stats(
[dbname] SYSNAME NULL,
[object_id]BIGINT NULL,
[xtp_object_id]BIGINT NULL,
[row_insert_attempts]BIGINT NULL,
[row_update_attempts]BIGINT NULL,
[row_delete_attempts]BIGINT NULL,
[write_conflicts]BIGINT NULL,
[unique_constraint_violations]BIGINT NULL,
[object_address] VARBINARY(8)
)
WHILE (@count<=@maxcount)
BEGIN
SELECT @database_id = database_id,
@dbname = dbname
FROM #db_inmemory
WHERE id = @count
IF (@sql_major_version >=13 )
BEGIN
SET @sql = N'USE [' + @dbname + '];
INSERT INTO #tmp_dm_db_xtp_object_stats
SELECT '''+@dbname+''',
[object_id],
[xtp_object_id],
[row_insert_attempts],
[row_update_attempts],
[row_delete_attempts],
[write_conflicts],
[unique_constraint_violations],
[object_address]
FROM sys.dm_db_xtp_object_stats;'
END
ELSE
BEGIN
SET @sql = N'USE [' + @dbname + '];
INSERT INTO #tmp_dm_db_xtp_object_stats
SELECT '''+@dbname+''',
[object_id],
NULL, --[xtp_object_id],
[row_insert_attempts],
[row_update_attempts],
[row_delete_attempts],
[write_conflicts],
[unique_constraint_violations],
[object_address]
FROM sys.dm_db_xtp_object_stats;'
END
--print @sql
EXEC (@sql)
SET @count = @count + 1
END
SELECT CONVERT (varchar(30), @runtime, 121) as runtime, * FROM #tmp_dm_db_xtp_object_stats
RAISERROR ('', 0, 1) WITH NOWAIT
--instance level in-memory dmvs
PRINT '-- sys.dm_xtp_system_memory_consumers --'
SELECT CONVERT (varchar(30), @runtime, 121) as runtime,
[memory_consumer_id],
[memory_consumer_type],
[memory_consumer_type_desc],
[memory_consumer_desc],
[lookaside_id],
[allocated_bytes],
[used_bytes],
[allocation_count],
[partition_count],
[sizeclass_count],
[min_sizeclass],
[max_sizeclass],
[memory_consumer_address]
FROM sys.dm_xtp_system_memory_consumers
WHERE allocated_bytes > 0
RAISERROR ('', 0, 1) WITH NOWAIT
PRINT '-- sys.dm_xtp_system_memory_consumers_summary --'
SELECT CONVERT (varchar(30), @runtime, 121) as runtime,
SUM(allocated_bytes) / (1024 * 1024) AS total_allocated_MB,
SUM(used_bytes) / (1024 * 1024) AS total_used_MB
FROM sys.dm_xtp_system_memory_consumers
RAISERROR ('', 0, 1) WITH NOWAIT
PRINT '-- sys.dm_xtp_gc_stats --'
SELECT CONVERT (varchar(30), @runtime, 121) as runtime,
[rows_examined],
[rows_no_sweep_needed],
[rows_first_in_bucket],
[rows_first_in_bucket_removed],
[rows_marked_for_unlink],
[parallel_assist_count],
[idle_worker_count],
[sweep_scans_started],
[sweep_scan_retries],
[sweep_rows_touched],
[sweep_rows_expiring],
[sweep_rows_expired],
[sweep_rows_expired_removed]
FROM sys.dm_xtp_gc_stats
RAISERROR ('', 0, 1) WITH NOWAIT
PRINT '-- sys.dm_xtp_gc_queue_stats --'
SELECT CONVERT (varchar(30), @runtime, 121) as runtime,
[queue_id],
[total_enqueues],
[total_dequeues],
[current_queue_depth],
[maximum_queue_depth],
[last_service_ticks]
FROM sys.dm_xtp_gc_queue_stats
ORDER BY current_queue_depth DESC
RAISERROR ('', 0, 1) WITH NOWAIT
END
ELSE
BEGIN
PRINT 'No XTP supported in this version of SQL Server'
RAISERROR ('', 0, 1) WITH NOWAIT
END
END TRY
BEGIN CATCH
PRINT 'Exception occured in: "' + OBJECT_NAME(@@PROCID) + '"'
PRINT 'Msg ' + isnull(cast(Error_Number() as nvarchar(50)), '') + ', Level ' + isnull(cast(Error_Severity() as nvarchar(50)),'') + ', State ' + isnull(cast(Error_State() as nvarchar(50)),'') + ', Server ' + @@servername + ', Line ' + isnull(cast(Error_Line() as nvarchar(50)),'') + char(10) + Error_Message() + char(10);
END CATCH
go
@ -405,20 +909,24 @@ set @sp_mem_stats_ver = 'sp_mem_stats' + @servermajorversion
print 'running memory collector ' + @sp_mem_stats_ver
WHILE (1=1)
BEGIN
BEGIN TRY
SET @runtime = GETDATE()
PRINT ''
PRINT 'Start time: ' + CONVERT (varchar (50), GETDATE(), 121)
PRINT ''
SET @runtime = GETDATE()
PRINT ''
PRINT 'Start time: ' + CONVERT (varchar (50), GETDATE(), 121)
PRINT ''
exec @sp_mem_stats_ver @runtime, @lastruntime
exec @sp_mem_stats_ver @runtime, @lastruntime
-- Save current runtime -- we'll use it to display only new ring buffer records on the next snapshot
SET @lastruntime = DATEADD (s, -15, @runtime) -- allow for up to a 15 second snapshot runtime without missing records
-- flush the buffer
RAISERROR ('', 0,1) WITH NOWAIT
WAITFOR DELAY @WaitForDelayString
-- Save current runtime -- we'll use it to display only new ring buffer records on the next snapshot
SET @lastruntime = DATEADD (s, -15, @runtime) -- allow for up to a 15 second snapshot runtime without missing records
-- flush the buffer
RAISERROR ('', 0,1) WITH NOWAIT
WAITFOR DELAY @WaitForDelayString
END TRY
BEGIN CATCH
PRINT 'Exception occured in: "' + OBJECT_NAME(@@PROCID) + '"'
PRINT 'Msg ' + isnull(cast(Error_Number() as nvarchar(50)), '') + ', Level ' + isnull(cast(Error_Severity() as nvarchar(50)),'') + ', State ' + isnull(cast(Error_State() as nvarchar(50)),'') + ', Server ' + @@servername + ', Line ' + isnull(cast(Error_Line() as nvarchar(50)),'') + char(10) + Error_Message() + char(10);
END CATCH
END
GO

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -0,0 +1,864 @@
USE tempdb
GO
SET NOCOUNT ON
SET QUOTED_IDENTIFIER ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
SET ARITHABORT ON
SET CONCAT_NULL_YIELDS_NULL ON
SET QUOTED_IDENTIFIER ON
SET NUMERIC_ROUNDABORT OFF
GO
/*******************************************************************
perf stats snapshot
********************************************************************/
use tempdb
go
IF OBJECT_ID ('#sp_perf_stats_snapshot','P') IS NOT NULL
DROP PROCEDURE #sp_perf_stats_snapshot
GO
CREATE PROCEDURE #sp_perf_stats_snapshot
as
begin
BEGIN TRY
PRINT 'Starting SQL Server Perf Stats Snapshot Script...'
PRINT 'SQL Version (SP) ' + CONVERT (varchar, SERVERPROPERTY ('ProductVersion')) + ' (' + CONVERT (varchar, SERVERPROPERTY ('ProductLevel')) + ')'
DECLARE @runtime datetime
DECLARE @cpu_time_start bigint, @cpu_time bigint, @elapsed_time_start bigint, @rowcount bigint
DECLARE @queryduration int, @qrydurationwarnthreshold int
DECLARE @querystarttime datetime
SET @runtime = GETDATE()
SET @qrydurationwarnthreshold = 5000
PRINT ''
PRINT 'Start time: ' + CONVERT (varchar(30), @runtime, 126)
PRINT ''
PRINT '-- Top N Query Plan Statistics --'
SELECT @cpu_time_start = cpu_time FROM sys.dm_exec_sessions WHERE session_id = @@SPID
SET @querystarttime = GETDATE()
SELECT
CONVERT (varchar(30), @runtime, 126) AS 'runtime',
LEFT (p.cacheobjtype + ' (' + p.objtype + ')', 35) AS 'cacheobjtype',
p.usecounts, p.size_in_bytes / 1024 AS 'size_in_kb',
PlanStats.total_worker_time/1000 AS 'tot_cpu_ms', PlanStats.total_elapsed_time/1000 AS 'tot_duration_ms',
PlanStats.total_physical_reads, PlanStats.total_logical_writes, PlanStats.total_logical_reads,
PlanStats.CpuRank, PlanStats.PhysicalReadsRank, PlanStats.DurationRank,
LEFT (CASE
WHEN pa.value=32767 THEN 'ResourceDb'
ELSE ISNULL (DB_NAME (CONVERT (sysname, pa.value)), CONVERT (sysname,pa.value))
END, 40) AS 'dbname',
sql.objectid,
CONVERT (nvarchar(50), CASE
WHEN sql.objectid IS NULL THEN NULL
ELSE REPLACE (REPLACE (sql.[text],CHAR(13), ' '), CHAR(10), ' ')
END) AS 'procname',
REPLACE (REPLACE (SUBSTRING (sql.[text], PlanStats.statement_start_offset/2 + 1,
CASE WHEN PlanStats.statement_end_offset = -1 THEN LEN (CONVERT(nvarchar(max), sql.[text]))
ELSE PlanStats.statement_end_offset/2 - PlanStats.statement_start_offset/2 + 1
END), CHAR(13), ' '), CHAR(10), ' ') AS 'stmt_text'
,PlanStats.query_hash, PlanStats.query_plan_hash, PlanStats.creation_time, PlanStats.statement_start_offset, PlanStats.statement_end_offset, PlanStats.plan_generation_num,
PlanStats.min_worker_time, PlanStats.last_worker_time, PlanStats.max_worker_time,
PlanStats.min_elapsed_time, PlanStats.last_elapsed_time, PlanStats.max_elapsed_time,
PlanStats.min_physical_reads, PlanStats.last_physical_reads, PlanStats.max_physical_reads,
PlanStats.min_logical_writes, PlanStats.last_logical_writes, PlanStats.max_logical_writes,
PlanStats.min_logical_reads, PlanStats.last_logical_reads, PlanStats.max_logical_reads,
PlanStats.plan_handle
FROM
(
SELECT
stat.plan_handle, statement_start_offset, statement_end_offset,
stat.total_worker_time, stat.total_elapsed_time, stat.total_physical_reads,
stat.total_logical_writes, stat.total_logical_reads,
stat.query_hash, stat.query_plan_hash, stat.plan_generation_num, stat.creation_time,
stat.last_worker_time, stat.min_worker_time, stat.max_worker_time, stat.last_elapsed_time, stat.min_elapsed_time, stat.max_elapsed_time,
stat.last_physical_reads, stat.min_physical_reads, stat.max_physical_reads, stat.last_logical_writes, stat.min_logical_writes, stat.max_logical_writes, stat.last_logical_reads, stat.min_logical_reads, stat.max_logical_reads,
ROW_NUMBER() OVER (ORDER BY stat.total_worker_time DESC) AS CpuRank,
ROW_NUMBER() OVER (ORDER BY stat.total_physical_reads DESC) AS PhysicalReadsRank,
ROW_NUMBER() OVER (ORDER BY stat.total_elapsed_time DESC) AS DurationRank
FROM sys.dm_exec_query_stats stat
) AS PlanStats
INNER JOIN sys.dm_exec_cached_plans p ON p.plan_handle = PlanStats.plan_handle
OUTER APPLY sys.dm_exec_plan_attributes (p.plan_handle) pa
OUTER APPLY sys.dm_exec_sql_text (p.plan_handle) AS sql
WHERE (PlanStats.CpuRank < 50 OR PlanStats.PhysicalReadsRank < 50 OR PlanStats.DurationRank < 50)
AND pa.attribute = 'dbid'
ORDER BY tot_cpu_ms DESC
OPTION (MAX_GRANT_PERCENT = 3, MAXDOP 1)
SET @rowcount = @@ROWCOUNT
SET @queryduration = DATEDIFF (ms, @querystarttime, GETDATE())
IF @queryduration > @qrydurationwarnthreshold
BEGIN
SELECT @cpu_time = cpu_time - @cpu_time_start FROM sys.dm_exec_sessions WHERE session_id = @@SPID
PRINT ''
PRINT 'DebugPrint: perfstats_snapshot_querystats - ' + CONVERT (varchar, @queryduration) + 'ms, '
+ CONVERT (varchar, @cpu_time) + 'ms cpu, '
+ 'rowcount=' + CONVERT(varchar, @rowcount)
PRINT ''
END
PRINT ''
PRINT '==============================================================================================='
PRINT 'Missing Indexes: '
PRINT 'The "improvement_measure" column is an indicator of the (estimated) improvement that might '
PRINT 'be seen if the index was created. This is a unitless number, and has meaning only relative '
PRINT 'the same number for other indexes. The measure is a combination of the avg_total_user_cost, '
PRINT 'avg_user_impact, user_seeks, and user_scans columns in sys.dm_db_missing_index_group_stats.'
PRINT ''
PRINT '-- Missing Indexes --'
SELECT CONVERT (varchar(30), @runtime, 126) AS runtime,
mig.index_group_handle, mid.index_handle,
CONVERT (decimal (28,1), migs.avg_total_user_cost * migs.avg_user_impact * (migs.user_seeks + migs.user_scans)) AS improvement_measure,
'CREATE INDEX missing_index_' + CONVERT (varchar, mig.index_group_handle) + '_' + CONVERT (varchar, mid.index_handle)
+ ' ON ' + mid.statement
+ ' (' + ISNULL (mid.equality_columns,'')
+ CASE WHEN mid.equality_columns IS NOT NULL AND mid.inequality_columns IS NOT NULL THEN ',' ELSE '' END + ISNULL (mid.inequality_columns, '')
+ ')'
+ ISNULL (' INCLUDE (' + mid.included_columns + ')', '') AS create_index_statement,
migs.*, mid.database_id, mid.[object_id]
FROM sys.dm_db_missing_index_groups mig
INNER JOIN sys.dm_db_missing_index_group_stats migs ON migs.group_handle = mig.index_group_handle
INNER JOIN sys.dm_db_missing_index_details mid ON mig.index_handle = mid.index_handle
WHERE CONVERT (decimal (28,1), migs.avg_total_user_cost * migs.avg_user_impact * (migs.user_seeks + migs.user_scans)) > 10
ORDER BY migs.avg_total_user_cost * migs.avg_user_impact * (migs.user_seeks + migs.user_scans) DESC
OPTION (MAX_GRANT_PERCENT = 3, MAXDOP 1)
PRINT ''
PRINT ''
PRINT '-- Current database options --'
SELECT LEFT ([name], 128) AS [name],
dbid, cmptlevel,
CONVERT (int, (SELECT SUM (CONVERT (bigint, [size])) * 8192 / 1024 / 1024 FROM master.sys.master_files f WHERE f.database_id = d.dbid)) AS db_size_in_mb,
LEFT (
'Status=' + CONVERT (sysname, DATABASEPROPERTYEX ([name],'Status'))
+ ', Updateability=' + CONVERT (sysname, DATABASEPROPERTYEX ([name],'Updateability'))
+ ', UserAccess=' + CONVERT (varchar(40), DATABASEPROPERTYEX ([name], 'UserAccess'))
+ ', Recovery=' + CONVERT (varchar(40), DATABASEPROPERTYEX ([name], 'Recovery'))
+ ', Version=' + CONVERT (varchar(40), DATABASEPROPERTYEX ([name], 'Version'))
+ CASE WHEN DATABASEPROPERTYEX ([name], 'IsAutoCreateStatistics') = 1 THEN ', IsAutoCreateStatistics' ELSE '' END
+ CASE WHEN DATABASEPROPERTYEX ([name], 'IsAutoUpdateStatistics') = 1 THEN ', IsAutoUpdateStatistics' ELSE '' END
+ CASE WHEN DATABASEPROPERTYEX ([name], 'IsShutdown') = 1 THEN '' ELSE ', Collation=' + CONVERT (varchar(40), DATABASEPROPERTYEX ([name], 'Collation')) END
+ CASE WHEN DATABASEPROPERTYEX ([name], 'IsAutoClose') = 1 THEN ', IsAutoClose' ELSE '' END
+ CASE WHEN DATABASEPROPERTYEX ([name], 'IsAutoShrink') = 1 THEN ', IsAutoShrink' ELSE '' END
+ CASE WHEN DATABASEPROPERTYEX ([name], 'IsInStandby') = 1 THEN ', IsInStandby' ELSE '' END
+ CASE WHEN DATABASEPROPERTYEX ([name], 'IsTornPageDetectionEnabled') = 1 THEN ', IsTornPageDetectionEnabled' ELSE '' END
+ CASE WHEN DATABASEPROPERTYEX ([name], 'IsAnsiNullDefault') = 1 THEN ', IsAnsiNullDefault' ELSE '' END
+ CASE WHEN DATABASEPROPERTYEX ([name], 'IsAnsiNullsEnabled') = 1 THEN ', IsAnsiNullsEnabled' ELSE '' END
+ CASE WHEN DATABASEPROPERTYEX ([name], 'IsAnsiPaddingEnabled') = 1 THEN ', IsAnsiPaddingEnabled' ELSE '' END
+ CASE WHEN DATABASEPROPERTYEX ([name], 'IsAnsiWarningsEnabled') = 1 THEN ', IsAnsiWarningsEnabled' ELSE '' END
+ CASE WHEN DATABASEPROPERTYEX ([name], 'IsArithmeticAbortEnabled') = 1 THEN ', IsArithmeticAbortEnabled' ELSE '' END
+ CASE WHEN DATABASEPROPERTYEX ([name], 'IsCloseCursorsOnCommitEnabled') = 1 THEN ', IsCloseCursorsOnCommitEnabled' ELSE '' END
+ CASE WHEN DATABASEPROPERTYEX ([name], 'IsFullTextEnabled') = 1 THEN ', IsFullTextEnabled' ELSE '' END
+ CASE WHEN DATABASEPROPERTYEX ([name], 'IsLocalCursorsDefault') = 1 THEN ', IsLocalCursorsDefault' ELSE '' END
+ CASE WHEN DATABASEPROPERTYEX ([name], 'IsNumericRoundAbortEnabled') = 1 THEN ', IsNumericRoundAbortEnabled' ELSE '' END
+ CASE WHEN DATABASEPROPERTYEX ([name], 'IsQuotedIdentifiersEnabled') = 1 THEN ', IsQuotedIdentifiersEnabled' ELSE '' END
+ CASE WHEN DATABASEPROPERTYEX ([name], 'IsRecursiveTriggersEnabled') = 1 THEN ', IsRecursiveTriggersEnabled' ELSE '' END
+ CASE WHEN DATABASEPROPERTYEX ([name], 'IsMergePublished') = 1 THEN ', IsMergePublished' ELSE '' END
+ CASE WHEN DATABASEPROPERTYEX ([name], 'IsPublished') = 1 THEN ', IsPublished' ELSE '' END
+ CASE WHEN DATABASEPROPERTYEX ([name], 'IsSubscribed') = 1 THEN ', IsSubscribed' ELSE '' END
+ CASE WHEN DATABASEPROPERTYEX ([name], 'IsSyncWithBackup') = 1 THEN ', IsSyncWithBackup' ELSE '' END
, 512) AS status
FROM master.dbo.sysdatabases d
PRINT ''
print '-- sys.dm_database_encryption_keys TDE --'
declare @sql_major_version INT, @sql_major_build INT, @sql nvarchar (max)
SELECT @sql_major_version = (CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS varchar(20)), 4) AS INT)),
@sql_major_build = (CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS varchar(20)), 2) AS INT))
set @sql = 'select DB_NAME(database_id) as ''database_name'',
[database_id]
,[encryption_state]
,[create_date]
,[regenerate_date]
,[modify_date]
,[set_date]
,[opened_date]
,[key_algorithm]
,[key_length]
,[encryptor_thumbprint]
,[percent_complete]'
IF (@sql_major_version >=11)
BEGIN
set @sql = @sql + ',[encryptor_type]'
END
IF (@sql_major_version >=15)
BEGIN
set @sql = @sql + '[encryption_state_desc]
,[encryption_scan_state]
,[encryption_scan_state_desc]
,[encryption_scan_modify_date]'
END
set @sql = @sql + ' from sys.dm_database_encryption_keys '
--print @sql
exec (@sql)
PRINT ''
print '-- sys.dm_server_audit_status --'
select
audit_id,
[name],
[status],
status_desc,
status_time,
event_session_address,
audit_file_path,
audit_file_size
from sys.dm_server_audit_status
print ''
print '-- top 10 CPU consuming procedures --'
SELECT TOP 10 getdate() as runtime, d.object_id, d.database_id, db_name(database_id) 'db name', object_name (object_id, database_id) 'proc name', d.cached_time, d.last_execution_time, d.total_elapsed_time, d.total_elapsed_time/d.execution_count AS [avg_elapsed_time], d.last_elapsed_time, d.execution_count
from sys.dm_exec_procedure_stats d
ORDER BY [total_worker_time] DESC
print ''
print '-- top 10 CPU consuming triggers --'
SELECT TOP 10 getdate() as runtime, d.object_id, d.database_id, db_name(database_id) 'db name', object_name (object_id, database_id) 'proc name', d.cached_time, d.last_execution_time, d.total_elapsed_time, d.total_elapsed_time/d.execution_count AS [avg_elapsed_time], d.last_elapsed_time, d.execution_count
from sys.dm_exec_trigger_stats d
ORDER BY [total_worker_time] DESC
print ''
--new stats DMV
set nocount on
declare @dbname sysname, @dbid int
SELECT @sql_major_version = (CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS varchar(20)), 4) AS INT)),
@sql_major_build = (CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS varchar(20)), 2) AS INT))
DECLARE dbCursor CURSOR FOR
select name, database_id from sys.databases where state_desc='ONLINE' and name not in ('model','tempdb') order by name
OPEN dbCursor
FETCH NEXT FROM dbCursor INTO @dbname, @dbid
--replaced sys.dm_db_index_usage_stats by sys.stat since the first doesn't return anything in case the table or index was not accessed since last SQL restart
select @dbid 'Database_Id', @dbname 'Database_Name', Object_name(st.object_id) 'Object_Name', SCHEMA_NAME(schema_id) 'Schema_Name', ss.name 'Statistics_Name',
st.object_id, st.stats_id, st.last_updated, st.rows, st.rows_sampled, st.steps, st.unfiltered_rows, st.modification_counter
into #tmpStats
from sys.stats ss cross apply sys.dm_db_stats_properties (ss.object_id, ss.stats_id) st inner join sys.objects so ON (ss.object_id = so.object_id) where 1=0
--column st.persisted_sample_percent was only introduced on sys.dm_db_stats_properties on SQL Server 2016 (13.x) SP1 CU4 -- 13.0.4446.0 and 2017 CU1 14.0.3006.16
IF (@sql_major_version >14 OR (@sql_major_version=13 AND @sql_major_build>=4446) OR (@sql_major_version=14 AND @sql_major_build>=3006))
BEGIN
ALTER TABLE #tmpStats ADD persisted_sample_percent FLOAT
END
WHILE @@FETCH_STATUS = 0
BEGIN
BEGIN TRY
set @sql = 'USE [' + @dbname + ']'
--replaced sys.dm_db_index_usage_stats by sys.stat since the first doesn't return anything in case the table or index was not accessed since last SQL restart
IF (@sql_major_version >14 OR (@sql_major_version=13 AND @sql_major_build>=4446) OR (@sql_major_version=14 AND @sql_major_build>=3006))
BEGIN
set @sql = @sql + ' insert into #tmpStats select ' + cast( @dbid as nvarchar(20)) + ' ''Database_Id''' + ',''' + @dbname + ''' Database_Name, Object_name(st.object_id) ''Object_Name'', SCHEMA_NAME(schema_id) ''Schema_Name'', ss.name ''Statistics_Name'',
st.object_id, st.stats_id, st.last_updated, st.rows, st.rows_sampled, st.steps, st.unfiltered_rows, st.modification_counter, st.persisted_sample_percent
from sys.stats ss
cross apply sys.dm_db_stats_properties (ss.object_id, ss.stats_id) st
inner join sys.objects so ON (ss.object_id = so.object_id)
where so.type not in (''S'', ''IT'')'
END
ELSE
BEGIN
set @sql = @sql + ' insert into #tmpStats select ' + cast( @dbid as nvarchar(20)) + ' ''Database_Id''' + ',''' + @dbname + ''' Database_Name, Object_name(st.object_id) ''Object_Name'', SCHEMA_NAME(schema_id) ''Schema_Name'', ss.name ''Statistics_Name'',
st.object_id, st.stats_id, st.last_updated, st.rows, st.rows_sampled, st.steps, st.unfiltered_rows, st.modification_counter
from sys.stats ss
cross apply sys.dm_db_stats_properties (ss.object_id, ss.stats_id) st
inner join sys.objects so ON (ss.object_id = so.object_id)
where so.type not in (''S'', ''IT'')'
END
-- added this check to prevent script from failing on principals with restricted access
if HAS_PERMS_BY_NAME(@dbname, 'DATABASE', 'CONNECT') = 1
exec (@sql)
else
PRINT 'Skipped index usage and stats properties check. Principal ' + SUSER_SNAME() + ' does not have CONNECT permission on database ' + @dbname
--print @sql
FETCH NEXT FROM dbCursor INTO @dbname, @dbid
END TRY
BEGIN CATCH
PRINT 'Exception occured in: "' + OBJECT_NAME(@@PROCID) + '"'
PRINT 'Msg ' + isnull(cast(Error_Number() as nvarchar(50)), '') + ', Level ' + isnull(cast(Error_Severity() as nvarchar(50)),'') + ', State ' + isnull(cast(Error_State() as nvarchar(50)),'') + ', Server ' + @@servername + ', Line ' + isnull(cast(Error_Line() as nvarchar(50)),'') + char(10) + Error_Message() + char(10);
END CATCH
END
close dbCursor
deallocate dbCursor
print ''
print '-- sys.dm_db_stats_properties --'
declare @sql2 nvarchar (max)
IF (@sql_major_version >14 OR (@sql_major_version=13 AND @sql_major_build>=4446) OR (@sql_major_version=14 AND @sql_major_build>=3006))
BEGIN
set @sql2 = 'select --*
Database_Id,
[Database_Name],
[Schema_Name],
[Object_Name],
[object_id],
[stats_id],
[Statistics_Name],
[last_updated],
[rows],
rows_sampled,
steps,
unfiltered_rows,
modification_counter,
persisted_sample_percent
from #tmpStats
order by [Database_Name]'
END
ELSE
BEGIN
set @sql2 = 'select --*
Database_Id,
[Database_Name],
[Schema_Name],
[Object_Name],
[object_id],
[stats_id],
[Statistics_Name],
[last_updated],
[rows],
rows_sampled,
steps,
unfiltered_rows,
modification_counter
from #tmpStats
order by [Database_Name]'
END
exec (@sql2)
drop table #tmpStats
print ''
--get disabled indexes
--import in SQLNexus
set nocount on
declare @dbname_index sysname, @dbid_index int
DECLARE dbCursor_Index CURSOR FOR
select QUOTENAME(name) name, database_id from sys.databases where state_desc='ONLINE' and database_id > 4 order by name
OPEN dbCursor_Index
FETCH NEXT FROM dbCursor_Index INTO @dbname_index, @dbid_index
select db_id() 'database_id', db_name() 'database_name', object_name(object_id) 'object_name', object_id,
name,
index_id,
type,
type_desc,
is_disabled into #tblDisabledIndex from sys.indexes where is_disabled = 1 and 1=0
WHILE @@FETCH_STATUS = 0
BEGIN
BEGIN TRY
declare @sql_index nvarchar (max)
set @sql_index = 'USE ' + @dbname_index
set @sql_index = @sql_index + ' insert into #tblDisabledIndex
select db_id() database_id,
db_name() database_name,
object_name(object_id) object_name,
object_id,
name,
index_id,
type,
type_desc,
is_disabled
from sys.indexes where is_disabled = 1'
-- added this check to prevent script from failing on principals with restricted access
if HAS_PERMS_BY_NAME(@dbname_index, 'DATABASE', 'CONNECT') = 1
exec (@sql_index)
else
PRINT 'Skipped disabled indexes check. Principal ' + SUSER_SNAME() + ' does not have CONNECT permission on database ' + @dbname
--print @sql
FETCH NEXT FROM dbCursor_Index INTO @dbname_index, @dbid_index
END TRY
BEGIN CATCH
PRINT 'Exception occured in: "' + OBJECT_NAME(@@PROCID) + '"'
PRINT 'Msg ' + isnull(cast(Error_Number() as nvarchar(50)), '') + ', Level ' + isnull(cast(Error_Severity() as nvarchar(50)),'') + ', State ' + isnull(cast(Error_State() as nvarchar(50)),'') + ', Server ' + @@servername + ', Line ' + isnull(cast(Error_Line() as nvarchar(50)),'') + char(10) + Error_Message() + char(10);
END CATCH
END
close dbCursor_Index
deallocate dbCursor_Index
print ''
print '--disabled indexes--'
select * from #tblDisabledIndex order by database_name
drop table #tblDisabledIndex
print ''
print '-- server_times --'
select CONVERT (varchar(30), getdate(), 126) as server_time, CONVERT (varchar(30), getutcdate(), 126) utc_time, DATEDIFF(hh, getutcdate(), getdate() ) time_delta_hours
/*
this takes too long for large machines
PRINT '-- High Compile Queries --';
WITH XMLNAMESPACES ('http://schemas.microsoft.com/sqlserver/2004/07/showplan' AS sp)
select
stmt.stmt_details.value ('(./sp:QueryPlan/@CompileTime)[1]', 'int') 'CompileTime',
stmt.stmt_details.value ('(./sp:QueryPlan/@CompileCPU)[1]', 'int') 'CompileCPU',
SUBSTRING(replace(replace(stmt.stmt_details.value ('@StatementText', 'nvarchar(max)'), char(13), ' '), char(10), ' '), 1, 8000) 'Statement'
from ( SELECT query_plan as sqlplan FROM sys.dm_exec_cached_plans AS qs CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle))
as p cross apply sqlplan.nodes('//sp:StmtSimple') as stmt (stmt_details)
order by 1 desc;
*/
RAISERROR ('', 0, 1) WITH NOWAIT;
END TRY
BEGIN CATCH
PRINT 'Exception occured in: "' + OBJECT_NAME(@@PROCID) + '"'
PRINT 'Msg ' + isnull(cast(Error_Number() as nvarchar(50)), '') + ', Level ' + isnull(cast(Error_Severity() as nvarchar(50)),'') + ', State ' + isnull(cast(Error_State() as nvarchar(50)),'') + ', Server ' + @@servername + ', Line ' + isnull(cast(Error_Line() as nvarchar(50)),'') + char(10) + Error_Message() + char(10);
END CATCH
END
GO
IF OBJECT_ID ('#sp_perf_stats_snapshot9','P') IS NOT NULL
DROP PROCEDURE #sp_perf_stats_snapshot9
GO
CREATE PROCEDURE #sp_perf_stats_snapshot9
AS
BEGIN
exec #sp_perf_stats_snapshot
END
GO
IF OBJECT_ID ('#sp_perf_stats_snapshot10','P') IS NOT NULL
DROP PROCEDURE #sp_perf_stats_snapshot10
GO
CREATE PROCEDURE #sp_perf_stats_snapshot10
AS
BEGIN
BEGIN TRY
exec #sp_perf_stats_snapshot9
print 'getting resource governor info'
print '=========================================='
print ''
print '-- sys.resource_governor_configuration --'
declare @sql_major_version INT, @sql_major_build INT, @sql nvarchar (max)
SELECT @sql_major_version = (CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS varchar(20)), 4) AS INT)),
@sql_major_build = (CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS varchar(20)), 2) AS INT))
BEGIN
SET @sql = 'select --*
classifier_function_id,
is_enabled'
IF (@sql_major_version >12)
BEGIN
SET @sql = @sql + ',[max_outstanding_io_per_volume]'
END
SET @sql = @sql + ' from sys.resource_governor_configuration;'
--print @sql
exec (@sql)
END
print ''
print '-- sys.resource_governor_resource_pools --'
SET @sql ='select --*
pool_id,
[name],
min_cpu_percent,
max_cpu_percent,
min_memory_percent,
max_memory_percent'
IF (@sql_major_version >=11)
BEGIN
SET @sql = @sql + ',cap_cpu_percent'
END
IF (@sql_major_version >=12)
BEGIN
SET @sql = @sql + ',min_iops_per_volume, max_iops_per_volume'
END
SET @sql = @sql + ' from sys.resource_governor_resource_pools;'
--print @sql
exec (@sql)
print ''
print '-- sys.resource_governor_workload_groups --'
SET @sql ='select --*
group_id,
[name],
importance,
request_max_memory_grant_percent,
request_max_cpu_time_sec,
request_memory_grant_timeout_sec,
max_dop,
group_max_requests,
pool_id'
IF (@sql_major_version >=13)
BEGIN
SET @sql = @sql + ',external_pool_id'
END
SET @sql = @sql + ' from sys.resource_governor_workload_groups'
--print @sql
exec (@sql)
print ''
print 'Query and plan hash capture '
--import in SQLNexus
print '-- top 10 CPU by query_hash --'
select getdate() as runtime, * --into tbl_QueryHashByCPU
from
(
SELECT TOP 10 query_hash, COUNT (distinct query_plan_hash) as 'distinct query_plan_hash count',
sum(execution_count) as 'execution_count',
sum(total_worker_time) as 'total_worker_time',
SUM(total_elapsed_time) as 'total_elapsed_time',
SUM (total_logical_reads) as 'total_logical_reads',
max(REPLACE (REPLACE (SUBSTRING (st.[text], qs.statement_start_offset/2 + 1,
CASE WHEN qs.statement_end_offset = -1 THEN LEN (CONVERT(nvarchar(max), st.[text]))
ELSE qs.statement_end_offset/2 - qs.statement_start_offset/2 + 1
END), CHAR(13), ' '), CHAR(10), ' ')) AS sample_statement_text
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st
group by query_hash
ORDER BY sum(total_worker_time) DESC
) t
OPTION (MAX_GRANT_PERCENT = 3, MAXDOP 1)
print ''
--import in SQLNexus
print '-- top 10 logical reads by query_hash --'
select getdate() as runtime, * --into tbl_QueryHashByLogicalReads
from
(
SELECT TOP 10 query_hash,
COUNT (distinct query_plan_hash) as 'distinct query_plan_hash count',
sum(execution_count) as 'execution_count',
sum(total_worker_time) as 'total_worker_time',
SUM(total_elapsed_time) as 'total_elapsed_time',
SUM (total_logical_reads) as 'total_logical_reads',
max(REPLACE (REPLACE (SUBSTRING (st.[text], qs.statement_start_offset/2 + 1,
CASE WHEN qs.statement_end_offset = -1 THEN LEN (CONVERT(nvarchar(max), st.[text]))
ELSE qs.statement_end_offset/2 - qs.statement_start_offset/2 + 1
END), CHAR(13), ' '), CHAR(10), ' ')) AS sample_statement_text
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st
group by query_hash
ORDER BY sum(total_logical_reads) DESC
) t
OPTION (MAX_GRANT_PERCENT = 3, MAXDOP 1)
print ''
--import in SQLNexus
print '-- top 10 elapsed time by query_hash --'
select getdate() as runtime, * -- into tbl_QueryHashByElapsedTime
from
(
SELECT TOP 10 query_hash,
sum(execution_count) as 'execution_count',
COUNT (distinct query_plan_hash) as 'distinct query_plan_hash count',
sum(total_worker_time) as 'total_worker_time',
SUM(total_elapsed_time) as 'total_elapsed_time',
SUM (total_logical_reads) as 'total_logical_reads',
max(REPLACE (REPLACE (SUBSTRING (st.[text], qs.statement_start_offset/2 + 1,
CASE WHEN qs.statement_end_offset = -1 THEN LEN (CONVERT(nvarchar(max), st.[text]))
ELSE qs.statement_end_offset/2 - qs.statement_start_offset/2 + 1
END), CHAR(13), ' '), CHAR(10), ' ')) AS sample_statement_text
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st
GROUP BY query_hash
ORDER BY sum(total_elapsed_time) DESC
) t
OPTION (MAX_GRANT_PERCENT = 3, MAXDOP 1)
print ''
--import in SQLNexus
print '-- top 10 CPU by query_plan_hash and query_hash --'
SELECT TOP 10 getdate() as runtime, query_plan_hash, query_hash,
COUNT (distinct query_plan_hash) as 'distinct query_plan_hash count',
sum(execution_count) as 'execution_count',
sum(total_worker_time) as 'total_worker_time',
SUM(total_elapsed_time) as 'total_elapsed_time',
SUM (total_logical_reads) as 'total_logical_reads',
max(REPLACE (REPLACE (SUBSTRING (st.[text], qs.statement_start_offset/2 + 1,
CASE WHEN qs.statement_end_offset = -1 THEN LEN (CONVERT(nvarchar(max), st.[text]))
ELSE qs.statement_end_offset/2 - qs.statement_start_offset/2 + 1
END), CHAR(13), ' '), CHAR(10), ' ')) AS sample_statement_text
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st
GROUP BY query_plan_hash, query_hash
ORDER BY sum(total_worker_time) DESC
OPTION (MAX_GRANT_PERCENT = 3, MAXDOP 1)
print ''
--import in SQLNexus
print '-- top 10 logical reads by query_plan_hash and query_hash --'
SELECT TOP 10 getdate() as runtime, query_plan_hash, query_hash, sum(execution_count) as 'execution_count',
sum(total_worker_time) as 'total_worker_time',
SUM(total_elapsed_time) as 'total_elapsed_time',
SUM (total_logical_reads) as 'total_logical_reads',
max(REPLACE (REPLACE (SUBSTRING (st.[text], qs.statement_start_offset/2 + 1,
CASE WHEN qs.statement_end_offset = -1 THEN LEN (CONVERT(nvarchar(max), st.[text]))
ELSE qs.statement_end_offset/2 - qs.statement_start_offset/2 + 1
END), CHAR(13), ' '), CHAR(10), ' ')) AS sample_statement_text
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st
group by query_plan_hash, query_hash
ORDER BY sum(total_logical_reads) DESC
OPTION (MAX_GRANT_PERCENT = 3, MAXDOP 1)
print ''
--import in SQLNexus
print '-- top 10 elapsed time by query_plan_hash and query_hash --'
SELECT TOP 10 getdate() as runtime, query_plan_hash, query_hash, sum(execution_count) as 'execution_count',
sum(total_worker_time) as 'total_worker_time',
SUM(total_elapsed_time) as 'total_elapsed_time',
SUM (total_logical_reads) as 'total_logical_reads',
max(REPLACE (REPLACE (SUBSTRING (st.[text], qs.statement_start_offset/2 + 1,
CASE WHEN qs.statement_end_offset = -1 THEN LEN (CONVERT(nvarchar(max), st.[text]))
ELSE qs.statement_end_offset/2 - qs.statement_start_offset/2 + 1
END), CHAR(13), ' '), CHAR(10), ' ')) AS sample_statement_text
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st
group by query_plan_hash, query_hash
ORDER BY sum(total_elapsed_time) DESC
OPTION (MAX_GRANT_PERCENT = 3, MAXDOP 1)
print ''
END TRY
BEGIN CATCH
PRINT 'Exception occured in: "' + OBJECT_NAME(@@PROCID) + '"'
PRINT 'Msg ' + isnull(cast(Error_Number() as nvarchar(50)), '') + ', Level ' + isnull(cast(Error_Severity() as nvarchar(50)),'') + ', State ' + isnull(cast(Error_State() as nvarchar(50)),'') + ', Server ' + @@servername + ', Line ' + isnull(cast(Error_Line() as nvarchar(50)),'') + char(10) + Error_Message() + char(10);
END CATCH
END
GO
IF OBJECT_ID ('#sp_perf_stats_snapshot11','P') IS NOT NULL
DROP PROCEDURE #sp_perf_stats_snapshot11
GO
CREATE PROCEDURE #sp_perf_stats_snapshot11
AS
BEGIN
exec #sp_perf_stats_snapshot10
END
GO
IF OBJECT_ID ('#sp_perf_stats_snapshot12','P') IS NOT NULL
DROP PROCEDURE #sp_perf_stats_snapshot12
GO
CREATE PROCEDURE #sp_perf_stats_snapshot12
as
BEGIN
exec #sp_perf_stats_snapshot11
END
GO
IF OBJECT_ID ('#sp_perf_stats_snapshot13','P') IS NOT NULL
DROP PROCEDURE #sp_perf_stats_snapshot13
GO
CREATE PROCEDURE #sp_perf_stats_snapshot13
AS
BEGIN
BEGIN TRY
exec #sp_perf_stats_snapshot12
IF OBJECT_ID ('sys.database_scoped_configurations') IS NOT NULL
BEGIN
PRINT '-- sys.database_scoped_configurations --'
DECLARE @database_id INT
DECLARE @dbname SYSNAME
DECLARE @cont INT
DECLARE @maxcont INT
DECLARE @sql_major_version INT
DECLARE @sql_major_build INT
DECLARE @sql nvarchar (max)
DECLARE @is_value_default BIT
DECLARE @dbtable TABLE (
id INT IDENTITY (1,1) PRIMARY KEY,
database_id INT,
dbname SYSNAME
)
SELECT @sql_major_version = (CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS VARCHAR(20)), 4) AS INT)),
@sql_major_build = (CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS VARCHAR(20)), 2) AS INT))
INSERT INTO @dbtable
SELECT database_id, name FROM sys.databases WHERE state_desc='ONLINE' AND name NOT IN ('model','tempdb') ORDER BY name
SET @cont = 1
SET @maxcont = (SELECT MAX(id) FROM @dbtable)
--create the schema
SELECT @database_id as database_id , @dbname as dbname, configuration_id, name, value, value_for_secondary, @is_value_default AS is_value_default
INTO #db_scoped_config
FROM sys.database_scoped_configurations
WHERE 1=0
--insert from all databases
WHILE (@cont<=@maxcont)
BEGIN
BEGIN TRY
SELECT @database_id = database_id,
@dbname = dbname
FROM @dbtable
WHERE id = @cont
SET @sql = 'USE [' + @dbname + ']'
IF (@sql_major_version > 13)
BEGIN
SET @sql = ' INSERT INTO #db_scoped_config SELECT ' + CONVERT(VARCHAR,@database_id) + ',''' + @dbname + ''', configuration_id, name, value, value_for_secondary, is_value_default FROM sys.database_scoped_configurations'
END
ELSE
BEGIN
SET @sql = ' INSERT INTO #db_scoped_config SELECT ' + CONVERT(VARCHAR,@database_id) + ',''' + @dbname + ''', configuration_id, name, value, value_for_secondary, NULL FROM sys.database_scoped_configurations'
END
--PRINT @sql
EXEC (@sql)
SET @cont = @cont + 1
END TRY
BEGIN CATCH
PRINT 'Exception occured in: "' + OBJECT_NAME(@@PROCID) + '"'
PRINT 'Msg ' + isnull(cast(Error_Number() as nvarchar(50)), '') + ', Level ' + isnull(cast(Error_Severity() as nvarchar(50)),'') + ', State ' + isnull(cast(Error_State() as nvarchar(50)),'') + ', Server ' + @@servername + ', Line ' + isnull(cast(Error_Line() as nvarchar(50)),'') + char(10) + Error_Message() + char(10);
END CATCH
END
SELECT
database_id,
CONVERT(VARCHAR(48), dbname) AS dbname,
configuration_id,
name,
CONVERT(VARCHAR(256), value) AS value,
CONVERT(VARCHAR(256),value_for_secondary) AS value_for_secondary,
is_value_default
FROM #db_scoped_config
PRINT ''
END
END TRY
BEGIN CATCH
PRINT 'Exception occured in: "' + OBJECT_NAME(@@PROCID) + '"'
PRINT 'Msg ' + isnull(cast(Error_Number() as nvarchar(50)), '') + ', Level ' + isnull(cast(Error_Severity() as nvarchar(50)),'') + ', State ' + isnull(cast(Error_State() as nvarchar(50)),'') + ', Server ' + @@servername + ', Line ' + isnull(cast(Error_Line() as nvarchar(50)),'') + char(10) + Error_Message() + char(10);
END CATCH
END
GO
IF OBJECT_ID ('#sp_perf_stats_snapshot14','P') IS NOT NULL
DROP PROCEDURE #sp_perf_stats_snapshot14
GO
CREATE PROCEDURE #sp_perf_stats_snapshot14
AS
BEGIN
exec #sp_perf_stats_snapshot13
END
GO
IF OBJECT_ID ('#sp_perf_stats_snapshot15','P') IS NOT NULL
DROP PROCEDURE #sp_perf_stats_snapshot15
GO
CREATE PROCEDURE #sp_perf_stats_snapshot15
AS
BEGIN
BEGIN TRY
exec #sp_perf_stats_snapshot14
declare @sql_major_version INT
SELECT @sql_major_version = (CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS varchar(20)), 4) AS INT))
-- Check the MS Version
IF (@sql_major_version >=15)
BEGIN
-- Add identifier
print '-- sys.index_resumable_operations --'
SELECT object_id, OBJECT_NAME(object_id) [object_name], index_id, name [index_name],
sql_text,last_max_dop_used, partition_number, state, state_desc, start_time,
last_pause_time, total_execution_time, percent_complete, page_count
FROM sys.index_resumable_operations
PRINT ''
RAISERROR ('', 0, 1) WITH NOWAIT
END
END TRY
BEGIN CATCH
PRINT 'Exception occured in: "' + OBJECT_NAME(@@PROCID) + '"'
PRINT 'Msg ' + isnull(cast(Error_Number() as nvarchar(50)), '') + ', Level ' + isnull(cast(Error_Severity() as nvarchar(50)),'') + ', State ' + isnull(cast(Error_State() as nvarchar(50)),'') + ', Server ' + @@servername + ', Line ' + isnull(cast(Error_Line() as nvarchar(50)),'') + char(10) + Error_Message() + char(10);
END CATCH
END
GO
IF OBJECT_ID ('#sp_perf_stats_snapshot16','P') IS NOT NULL
DROP PROCEDURE #sp_perf_stats_snapshot16
GO
CREATE PROCEDURE #sp_perf_stats_snapshot16
AS
BEGIN
exec #sp_perf_stats_snapshot15
END
GO
/*****************************************************************
* main loop perf statssnapshot *
******************************************************************/
IF OBJECT_ID ('#sp_Run_PerfStats_Snapshot','P') IS NOT NULL
DROP PROCEDURE #sp_Run_PerfStats_Snapshot
GO
CREATE PROCEDURE #sp_Run_PerfStats_Snapshot @IsLite bit=0
AS
BEGIN TRY
DECLARE @servermajorversion nvarchar(2)
SET @servermajorversion = REPLACE (LEFT (CONVERT (varchar, SERVERPROPERTY ('ProductVersion')), 2), '.', '')
declare @#sp_perf_stats_snapshot_ver sysname
set @#sp_perf_stats_snapshot_ver = '#sp_perf_stats_snapshot' + @servermajorversion
print 'executing procedure ' + @#sp_perf_stats_snapshot_ver
exec @#sp_perf_stats_snapshot_ver
END TRY
BEGIN CATCH
PRINT 'Exception occured in: "' + OBJECT_NAME(@@PROCID) + '"'
PRINT 'Msg ' + isnull(cast(Error_Number() as nvarchar(50)), '') + ', Level ' + isnull(cast(Error_Severity() as nvarchar(50)),'') + ', State ' + isnull(cast(Error_State() as nvarchar(50)),'') + ', Server ' + @@servername + ', Line ' + isnull(cast(Error_Line() as nvarchar(50)),'') + char(10) + Error_Message() + char(10);
END CATCH
GO
exec #sp_Run_PerfStats_Snapshot

Просмотреть файл

@ -1,25 +1,3 @@
/*
Author: EricBu@Microsoft.com and wcarroll@microsoft.com
Purpose: Service Broker Script for PSSDiag
Date: 05/18/2015
Note: Set osql -w 8000 in order to display entire definition of activation stored procedures. Save Output as text.
Version: 2.0
Change List:
EricBu - Changed table delimiter so tables can be imported via SQL Nexus Custom Row Importer
EricBu - Changed all code to NOLOCKs to reduce blocking
EricBu - Changed sys.database query to only return databases with SSB activated.
EricBu - Changed sys.dm_broker_queue_monitors to show current state, last activation, current backlog in transmission queue
EricBu - Changed COUNT(*) to point to meta data rather than table to reduce data collection time/size as we don't need the count to be 100% accurate.
EricBu - Changed output to be more readable.
EricBu - Changed the sys.transmission_queue output to remove the Message field which likely will have PPI information in it.
EricBu - Added DB_NAME() column to sys.transmission and sys.conversation_endpoints queries, so custom importer will import all data from each SSB DB and we can query on them.
EricBu - Added time to track how long it takes to gather data from each database. We may spot performance issues with gathering data this way.
EricBu - Changed context of the Queue Monitor Query to the Database Context
EricBu - Added GROUPing Counts to sys.transmission_queue and sys.conversation_endpoints.
EricBu - Fixed DATEDIFF() call for the SSB Database specific time.
*/
USE master
go
@ -27,9 +5,14 @@ SET NOCOUNT ON
SET QUOTED_IDENTIFIER ON;
DECLARE @StartTime datetime
select @@version as 'Version'
PRINT ''
select GETDATE() as 'RunDateTime', GETUTCDATE() as 'RunUTCDateTime', SYSDATETIMEOFFSET() as 'SysDateTimeOffset'
PRINT ''
select @@servername as 'ServerName'
PRINT ''
PRINT '-- sys.databases --'
select * from master.sys.databases where is_broker_enabled = 1 and name not in('tempdb', 'model', 'AdventureWorks', 'AdventureWorksDW')
PRINT ''
@ -86,7 +69,7 @@ BEGIN
SELECT @SCI = 0; -- service_contract_id
select @dbname = RTRIM(@dbname);
EXEC ('USE [' + @dbname + ']');
SELECT @cmd3 = N'SELECT @SCI_OUT = MAX(service_contract_id) FROM ' + @dbname + '.sys.service_contracts';
SELECT @cmd3 = N'SELECT @SCI_OUT = MAX(service_contract_id) FROM [' + @dbname + '].sys.service_contracts';
EXEC sp_executesql @cmd3, N'@SCI_OUT INT OUTPUT', @SCI_OUT = @SCI OUTPUT;
IF @SCI > 7
BEGIN
@ -109,7 +92,7 @@ BEGIN
EXEC ('SELECT * FROM ' + @dbname + '.sys.service_contracts');
-- PRINT ''
-- print '-- sys.service_contract_usages --'
-- PRINT '-- sys.service_contract_usages --'
-- EXEC ('SELECT * FROM ' + @dbname + '.sys.service_contract_usages');
PRINT ''
@ -149,7 +132,7 @@ BEGIN
CONVERT(VARCHAR(512),subject) AS subject,
expiry_date,
start_date,
''0x'' + CONVERT(VARCHAR(64),thumbprint,2) AS thumbprint,
''0x'' + CONVERT(VARCHAR(64),thumbPRINT,2) AS thumbPRINT,
CONVERT(VARCHAR(256), attested_by) AS attested_by,
pvt_key_last_backup_date,
key_length
@ -202,13 +185,13 @@ BEGIN
PRINT ''
PRINT 'TOP 500'
print '-- sys.transmission_queue --'
PRINT '-- sys.transmission_queue --'
EXEC ('USE ' + @dbname + ';SELECT top 500 conversation_handle, to_service_name, to_broker_instance, from_service_name,
service_contract_name, enqueue_time, message_sequence_number, message_type_name, is_conversation_error,
is_end_of_dialog, priority, transmission_status, DB_NAME() as DB_Name FROM ' + @dbname + '.sys.transmission_queue with (nolock) order by enqueue_time, message_sequence_number');
PRINT ''
print 'sys.conversation_endpoints (total count, group count, and top 500)'
PRINT 'sys.conversation_endpoints (total count, group count, and top 500)'
-- Using count against MetaData columns rather than COUNT(*) becuase it is faster, and we dont' need exact counts
PRINT '-- TOTAL COUNT sys.conversation_endpoints --'
EXEC ('SELECT p.rows as CE_Count FROM ' + @dbname + '.sys.objects as o join ' + @dbname + '.sys.partitions as p on p.object_id = o.object_id where o.name = ''sysdesend''')
@ -265,4 +248,123 @@ CLOSE tnames_cursor;
DEALLOCATE tnames_cursor;
PRINT 'Getting Database Mail Information'
PRINT ''
PRINT '-- sysmail_event_log_sysmail_faileditems --'
SELECT er.log_id,
er.event_type,
er.log_date,
er.description,
er.process_id,
er.mailitem_id,
er.account_id,
er.last_mod_date,
er.last_mod_user,
fi.send_request_user,
fi.send_request_date,
fi.recipients,
fi.subject,
fi.body
FROM msdb.dbo.sysmail_event_log er
LEFT JOIN msdb.dbo.sysmail_faileditems fi
ON er.mailitem_id = fi.mailitem_id
ORDER BY log_date DESC;
RAISERROR (' ', 0, 1) WITH NOWAIT;
PRINT '-- sysmail_mailitems --'
SELECT mailitem_id,
profile_id,
recipients,
copy_recipients,
blind_copy_recipients,
subject,
from_address,
body,
body_format,
importance,
sensitivity,
file_attachments,
attachment_encoding,
query,
execute_query_database,
attach_query_result_as_file,
query_result_header,
query_result_width,
query_result_separator,
exclude_query_output,
append_query_error,
send_request_date,
send_request_user,
sent_account_id,
CASE sent_status
WHEN 0 THEN 'unsent'
WHEN 1 THEN 'sent'
WHEN 3 THEN 'retrying'
ELSE 'failed'
END as sent_status_description,
sent_status,
sent_date,
last_mod_date,
last_mod_user
FROM msdb.dbo.sysmail_mailitems;
RAISERROR (' ', 0, 1) WITH NOWAIT;
PRINT '-- sysmail_account --'
SELECT
account_id ,
name ,
description ,
email_address ,
display_name ,
replyto_address ,
last_mod_datetime ,
last_mod_user
FROM msdb.dbo.sysmail_account;
RAISERROR (' ', 0, 1) WITH NOWAIT;
PRINT '-- sysmail_configuration --'
SELECT
paramname ,
paramvalue ,
description ,
last_mod_datetime ,
last_mod_user
FROM msdb.dbo.sysmail_configuration;
RAISERROR (' ', 0, 1) WITH NOWAIT;
PRINT '-- sysmail_log --'
SELECT
log_id ,
event_type ,
log_date ,
description ,
process_id ,
mailitem_id ,
account_id ,
last_mod_date ,
last_mod_user
FROM msdb.dbo.sysmail_log;
RAISERROR (' ', 0, 1) WITH NOWAIT;
PRINT '-- sysmail_profile --'
SELECT
profile_id ,
name ,
description ,
last_mod_datetime ,
last_mod_user
FROM msdb.dbo.sysmail_profile
RAISERROR (' ', 0, 1) WITH NOWAIT;
PRINT '-- sysmail_profileaccount --'
SELECT
profile_id ,
account_id ,
sequence_number ,
last_mod_datetime ,
last_mod_user
FROM
msdb.dbo.sysmail_profileaccount
RAISERROR (' ', 0, 1) WITH NOWAIT;

Просмотреть файл

@ -124,7 +124,7 @@ function Initialize-ScheduledTaskLog
$LogFileNameStringToDelete = $LogFileName
#update file with date
$LogFileName = ($LogFileName -replace "##SQLLogScout_ScheduledTask", ("##SQLLogScout_ScheduledTask_" + @(Get-Date -Format "yyyMMddTHHmmssffff") + ".log"))
$LogFileName = ($LogFileName -replace "##SQLLogScout_ScheduledTask", ("##SQLLogScout_ScheduledTask_" + @(Get-Date -Format "yyyyMMddTHHmmssffff") + ".log"))
$global:ScheduledTaskLog = $LogFilePath + '\' + $LogFileName
New-Item -ItemType "file" -Path $global:ScheduledTaskLog -Force | Out-Null
$CurrentTime = (Get-Date -Format("yyyy-MM-dd HH:MM:ss.ms"))

Просмотреть файл

@ -0,0 +1,267 @@
function getSQLVersionsTBL {
return @{
"2022RTMCU11"=16000004105;
"2022RTMCU10"=16000004095;
"2022RTMCU9"=16000004085;
"2022RTMCU8"=16000004075;
"2022RTMCU7"=16000004065;
"2022RTMCU6"=16000004055;
"2022RTMCU5"=16000004045;
"2022RTMCU4"=16000004035;
"2022RTMCU3"=16000004025;
"2022RTMCU2"=16000004015;
"2022RTMCU1"=16000004003;
"2022RTM"=16000001000;
"2019RTMCU24"=15000004345;
"2019RTMCU23"=15000004335;
"2019RTMCU22"=15000004322;
"2019RTMCU21"=15000004316;
"2019RTMCU20"=15000004312;
"2019RTMCU19"=15000004298;
"2019RTMCU18"=15000004261;
"2019RTMCU17"=15000004249;
"2019RTMCU16"=15000004223;
"2019RTMCU15"=15000004198;
"2019RTMCU14"=15000004188;
"2019RTMCU13"=15000004178;
"2019RTMCU12"=15000004153;
"2019RTMCU11"=15000004138;
"2019RTMCU10"=15000004123;
"2019RTMCU9"=15000004102;
"2019RTMCU8"=15000004073;
"2019RTMCU7"=15000004063;
"2019RTMCU6"=15000004053;
"2019RTMCU5"=15000004043;
"2019RTMCU4"=15000004033;
"2019RTMCU3"=15000004023;
"2019RTMCU2"=15000004013;
"2019RTMCU1"=15000004003;
"2019RTM"=15000002000;
"2017RTMCU31"=14000003456;
"2017RTMCU30"=14000003451;
"2017RTMCU29"=14000003436;
"2017RTMCU28"=14000003430;
"2017RTMCU27"=14000003421;
"2017RTMCU26"=14000003411;
"2017RTMCU25"=14000003401;
"2017RTMCU24"=14000003391;
"2017RTMCU23"=14000003381;
"2017RTMCU22"=14000003356;
"2017RTMCU21"=14000003335;
"2017RTMCU20"=14000003294;
"2017RTMCU19"=14000003281;
"2017RTMCU18"=14000003257;
"2017RTMCU17"=14000003238;
"2017RTMCU16"=14000003223;
"2017RTMCU15"=14000003162;
"2017RTMCU14"=14000003076;
"2017RTMCU13"=14000003048;
"2017RTMCU12"=14000003045;
"2017RTMCU11"=14000003038;
"2017RTMCU10"=14000003037;
"2017RTMCU9"=14000003030;
"2017RTMCU8"=14000003029;
"2017RTMCU7"=14000003026;
"2017RTMCU6"=14000003025;
"2017RTMCU5"=14000003023;
"2017RTMCU4"=14000003022;
"2017RTMCU3"=14000003015;
"2017RTMCU2"=14000003008;
"2017RTMCU1"=14000003006;
"2017RTM"=14000001000;
"2016SP3RTM"=13000006300;
"2016SP2CU17"=13000005888;
"2016SP2CU16"=13000005882;
"2016SP2CU15"=13000005850;
"2016SP2CU14"=13000005830;
"2016SP2CU13"=13000005820;
"2016SP2CU12"=13000005698;
"2016SP2CU11"=13000005598;
"2016SP2CU10"=13000005492;
"2016SP2CU8"=13000005426;
"2016SP2CU7"=13000005337;
"2016SP1CU15"=13000004574;
"2016SP2CU6"=13000005292;
"2016SP1CU14"=13000004560;
"2016SP2CU5"=13000005264;
"2016SP1CU13"=13000004550;
"2016SP2CU4"=13000005233;
"2016SP1CU12"=13000004541;
"2016SP2CU3"=13000005216;
"2016SP1CU11"=13000004528;
"2016SP2CU2"=13000005153;
"2016SP1CU10"=13000004514;
"2016SP2CU1"=13000005149;
"2016SP1CU9"=13000004502;
"2016SP2RTM"=13000005026;
"2016SP1CU8"=13000004474;
"2016SP1CU6"=13000004457;
"2016RTMCU9"=13000002216;
"2016SP1CU5"=13000004451;
"2016RTMCU8"=13000002213;
"2016SP1CU4"=13000004446;
"2016RTMCU7"=13000002210;
"2016SP1CU3"=13000004435;
"2016RTMCU6"=13000002204;
"2016SP1CU2"=13000004422;
"2016RTMCU5"=13000002197;
"2016SP1CU1"=13000004411;
"2016RTMCU4"=13000002193;
"2016RTMCU3"=13000002186;
"2016SP1RTM"=13000004001;
"2016RTMCU2"=13000002164;
"2016RTMCU1"=13000002149;
"2016RTM"=13000001601;
"2014SP3CU4"=12000006329;
"2014SP2CU18"=12000005687;
"2014SP3CU3"=12000006259;
"2014SP2CU17"=12000005632;
"2014SP3CU2"=12000006214;
"2014SP2CU16"=12000005626;
"2014SP3CU1"=12000006205;
"2014SP2CU15"=12000005605;
"2014SP3RTM"=12000006024;
"2014SP2CU14"=12000005600;
"2014SP2CU13"=12000005590;
"2014SP2CU12"=12000005589;
"2014SP2CU11"=12000005579;
"2014SP2CU9"=12000005563;
"2014SP2CU8"=12000005557;
"2014SP2CU7"=12000005556;
"2014SP2CU6"=12000005553;
"2014SP1CU13"=12000004522;
"2014SP1CU12"=12000004511;
"2014SP2CU5"=12000005546;
"2014SP2CU4"=12000005540;
"2014SP1CU11"=12000004502;
"2014SP2CU3"=12000005538;
"2014SP1CU10"=12000004491;
"2014SP2CU2"=12000005522;
"2014SP1CU9"=12000004474;
"2014SP2CU1"=12000005511;
"2014SP1CU8"=12000004468;
"2014SP2RTM"=12000005000;
"2014SP1CU7"=12000004459;
"2014RTMCU14"=12000002569;
"2014SP1CU6"=12000004457;
"2014RTMCU13"=12000002568;
"2014SP1CU5"=12000004439;
"2014RTMCU12"=12000002564;
"2014SP1CU4"=12000004436;
"2014RTMCU11"=12000002560;
"2014SP1CU3"=12000004427;
"2014RTMCU10"=12000002556;
"2014SP1CU2"=12000004422;
"2014RTMCU9"=12000002553;
"2014SP1CU1"=12000004416;
"2014RTMCU8"=12000002546;
"2014SP1RTM"=12000004100;
"2014RTMCU7"=12000002495;
"2014RTMCU6"=12000002480;
"2014RTMCU5"=12000002456;
"2014RTMCU4"=12000002430;
"2014RTMCU3"=12000002402;
"2014RTMCU2"=12000002370;
"2014RTMCU1"=12000002342;
"2014RTM"=12000002000;
"2012SP4RTM"=11000007001;
"2012SP3CU10"=11000006607;
"2012SP3CU9"=11000006598;
"2012SP3CU8"=11000006594;
"2012SP2CU16"=11000005678;
"2012SP3CU7"=11000006579;
"2012SP3CU6"=11000006567;
"2012SP2CU15"=11000005676;
"2012SP3CU5"=11000006544;
"2012SP2CU14"=11000005657;
"2012SP3CU4"=11000006540;
"2012SP2CU13"=11000005655;
"2012SP3CU3"=11000006537;
"2012SP2CU12"=11000005649;
"2012SP3CU2"=11000006523;
"2012SP2CU11"=11000005646;
"2012SP3CU1"=11000006518;
"2012SP2CU10"=11000005644;
"2012SP3RTM"=11000006020;
"2012SP2CU9"=11000005641;
"2012SP2CU8"=11000005634;
"2012SP2CU7"=11000005623;
"2012SP2RTM"=11000005058;
"2012SP2CU6"=11000005592;
"2012SP2CU5"=11000005582;
"2012SP2CU4"=11000005569;
"2012SP2CU3"=11000005556;
"2012SP1CU13"=11000003482;
"2012SP2CU2"=11000005548;
"2012SP1CU12"=11000003470;
"2012SP2CU1"=11000005532;
"2012SP1CU11"=11000003449;
"2012SP1CU10"=11000003431;
"2012SP1CU9"=11000003412;
"2012SP1CU8"=11000003401;
"2012RTMCU11"=11000002424;
"2012SP1CU7"=11000003393;
"2012RTMCU10"=11000002420;
"2012SP1CU6"=11000003381;
"2012RTMCU9"=11000002419;
"2012SP1CU5"=11000003373;
"2012RTMCU8"=11000002410;
"2012SP1CU4"=11000003368;
"2012RTMCU7"=11000002405;
"2012SP1CU3"=11000003349;
"2012RTMCU6"=11000002401;
"2012SP1CU2"=11000003339;
"2012RTMCU5"=11000002395;
"2012SP1CU1"=11000003321;
"2012SP1RTM"=11000003000;
"2012RTMCU4"=11000002383;
"2012RTMCU3"=11000002332;
"2012RTMCU2"=11000002325;
"2012RTMCU1"=11000002316;
"2012RTM"=11000002100;
"2008R2SP3RTM"=10050006000;
"2008R2SP2CU12"=10050004305;
"2008R2SP2CU13"=10050004319;
"2008R2SP2CU11"=10050004302;
"2008R2SP2CU10"=10050004297;
"2008R2SP2CU9"=10050004295;
"2008R2SP2CU8"=10050004290;
"2008R2SP1CU14"=10050002881;
"2008R2SP2CU7"=10050004286;
"2008R2SP1CU13"=10050002876;
"2008R2SP2CU6"=10050004279;
"2008R2SP1CU12"=10050002874;
"2008R2SP2CU5"=10050004276;
"2008R2SP1CU11"=10050002869;
"2008R2SP2CU4"=10050004270;
"2008R2SP1CU10"=10050002868;
"2008R2SP2CU3"=10050004266;
"2008R2SP1CU9"=10050002866;
"2008R2SP2CU2"=10050004263;
"2008R2SP1CU8"=10050002822;
"2008R2SP2RTM"=10050004000;
"2008R2SP2CU1"=10050004260;
"2008R2SP1CU7"=10050002817;
"2008R2SP1CU6"=10050002811;
"2008R2RTMCU13"=10050001815;
"2008R2SP1CU5"=10050002806;
"2008R2RTMCU12"=10050001810;
"2008R2SP1CU4"=10050002796;
"2008R2RTMCU11"=10050001809;
"2008R2SP1CU3"=10050002789;
"2008R2RTMCU10"=10050001807;
"2008R2SP1CU2"=10050002772;
"2008R2RTMCU9"=10050001804;
"2008R2SP1CU1"=10050002769;
"2008R2SP1RTM"=10050002500;
"2008R2RTMCU8"=10050001797;
"2008R2RTMCU7"=10050001777;
"2008R2RTMCU6"=10050001765;
"2008R2RTMCU5"=10050001753;
"2008R2RTMCU4"=10050001746;
"2008R2RTMCU3"=10050001734;
"2008R2RTMCU2"=10050001720;
"2008R2RTMCU1"=10050001702;
"2008R2RTM"=10050001600;
}
}

Просмотреть файл

@ -9,62 +9,71 @@ SELECT @sql_major_version = (CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion'
WHILE 1=1
BEGIN
PRINT '-- Current time'
SELECT getdate()
IF OBJECT_ID('tempdb..#dbtable') IS NOT NULL
DROP TABLE #dbtable;
IF OBJECT_ID('tempdb..#db_inmemory') IS NOT NULL
DROP TABLE #db_inmemory;
IF OBJECT_ID('tempdb..#tmp_dm_db_xtp_transactions ') IS NOT NULL
DROP TABLE #tmp_dm_db_xtp_transactions;
PRINT '-- Current time'
SELECT getdate()
PRINT ''
DECLARE @runtime datetime
SET @runtime = CONVERT (varchar(30), GETDATE(), 121)
DECLARE @runtime datetime
SET @runtime = CONVERT (varchar(30), GETDATE(), 121)
PRINT '-- sys.dm_db_file_space_usage --'
SELECT @runtime AS runtime,
DB_NAME() AS dbname,
SUM (user_object_reserved_page_count)*8 AS usr_obj_kb,
SUM (internal_object_reserved_page_count)*8 AS internal_obj_kb,
SUM (version_store_reserved_page_count)*8 AS version_store_kb,
SUM (unallocated_extent_page_count)*8 AS freespace_kb,
SUM (mixed_extent_page_count)*8 AS mixedextent_kb
FROM sys.dm_db_file_space_usage
OPTION (max_grant_percent = 3, MAXDOP 2)
PRINT ''
PRINT '-- sys.dm_db_file_space_usage --'
SELECT @runtime AS runtime,
DB_NAME() AS dbname,
SUM (user_object_reserved_page_count)*8 AS usr_obj_kb,
SUM (internal_object_reserved_page_count)*8 AS internal_obj_kb,
SUM (version_store_reserved_page_count)*8 AS version_store_kb,
SUM (unallocated_extent_page_count)*8 AS freespace_kb,
SUM (mixed_extent_page_count)*8 AS mixedextent_kb
FROM sys.dm_db_file_space_usage
OPTION (max_grant_percent = 3, MAXDOP 2)
PRINT ''
PRINT '-- tempdb_space_usage_by_file --'
SELECT @runtime AS runtime,
SUBSTRING(name, 0, 32) AS filename,
physical_name,
CONVERT(decimal(10,3),size/128.0) AS currentsize_mb,
CONVERT(decimal(10,3),size/128.0 - FILEPROPERTY(name, 'SpaceUsed')/128.0) AS freespace_mb
FROM tempdb.sys.database_files f
PRINT ''
PRINT '-- tempdb_space_usage_by_file --'
SELECT @runtime AS runtime,
SUBSTRING(name, 0, 32) AS filename,
physical_name,
CONVERT(decimal(10,3),size/128.0) AS currentsize_mb,
CONVERT(decimal(10,3),size/128.0 - FILEPROPERTY(name, 'SpaceUsed')/128.0) AS freespace_mb
FROM tempdb.sys.database_files f
PRINT ''
PRINT '-- transaction_perfmon_counters --'
SELECT @runtime AS runtime,
CONVERT(VARCHAR(16), DB_NAME ()) AS dbname,
SUBSTRING(object_name,0,28) as object_name,
SUBSTRING(counter_name,0,42) as counter_name,
cntr_value AS counter_value
FROM sys.dm_os_performance_counters
WHERE Object_Name LIKE '%:Transactions%'
SELECT @runtime AS runtime,
CONVERT(VARCHAR(16), DB_NAME ()) AS dbname,
SUBSTRING(object_name,0,28) as object_name,
SUBSTRING(counter_name,0,42) as counter_name,
cntr_value AS counter_value
FROM sys.dm_os_performance_counters
WHERE Object_Name LIKE '%:Transactions%'
RAISERROR ('', 0, 1) WITH NOWAIT
PRINT ''
RAISERROR ('', 0, 1) WITH NOWAIT
PRINT ''
PRINT '-- sys.dm_db_session_space_usage --'
SELECT TOP 10 @runtime AS runtime,
su.session_id,
su.database_id,
su.internal_objects_alloc_page_count,
su.internal_objects_dealloc_page_count,
su.user_objects_alloc_page_count,
su.user_objects_dealloc_page_count,
su.user_objects_deferred_dealloc_page_count,
s.open_transaction_count,
s.last_request_end_time,
SUBSTRING(s.host_name, 0, 48) host_name,
SUBSTRING(s.program_name,0,48) program_name,
LTRIM(RTRIM(REPLACE(REPLACE(SUBSTRING(t.text, 0,256), CHAR(10), ' '), CHAR(13), ' '))) AS most_recent_query
FROM sys.dm_db_session_space_usage su
PRINT '-- sys.dm_db_session_space_usage --'
SELECT TOP 10 @runtime AS runtime,
su.session_id,
su.database_id,
su.internal_objects_alloc_page_count,
su.internal_objects_dealloc_page_count,
su.user_objects_alloc_page_count,
su.user_objects_dealloc_page_count,
su.user_objects_deferred_dealloc_page_count,
s.open_transaction_count,
s.last_request_end_time,
SUBSTRING(s.host_name, 0, 48) host_name,
SUBSTRING(s.program_name,0,48) program_name,
LTRIM(RTRIM(REPLACE(REPLACE(SUBSTRING(t.text, 0,256), CHAR(10), ' '), CHAR(13), ' '))) AS most_recent_query
FROM sys.dm_db_session_space_usage su
LEFT OUTER JOIN sys.dm_exec_sessions s
ON su.session_id = s.session_id
LEFT OUTER JOIN sys.dm_exec_connections c
@ -76,158 +85,154 @@ BEGIN
PRINT ''
PRINT '-- sys.dm_db_task_space_usage --'
SELECT TOP 10 @runtime AS runtime,
tsu.session_id,
tsu.database_id,
tsu.internal_objects_alloc_page_count,
tsu.internal_objects_dealloc_page_count,
tsu.user_objects_alloc_page_count,
tsu.user_objects_dealloc_page_count,
tsu.exec_context_id,
r.status,
r.wait_type,
r.wait_time,
r.cpu_time,
LTRIM(RTRIM(REPLACE(REPLACE(SUBSTRING(t.text, (r.statement_start_offset/2)+1,
((CASE r.statement_end_offset
WHEN -1 THEN DATALENGTH(t.text)
ELSE r.statement_end_offset
END - r.statement_start_offset)/2) + 1), CHAR(10), ' '), CHAR(13), ' '))) AS statement_text,
LTRIM(RTRIM(REPLACE(REPLACE(SUBSTRING(t.text, 0,256), CHAR(10), ' '), CHAR(13), ' '))) AS batch_text
FROM sys.dm_db_task_space_usage tsu
PRINT '-- sys.dm_db_task_space_usage --'
SELECT TOP 10 @runtime AS runtime,
tsu.session_id,
tsu.database_id,
tsu.internal_objects_alloc_page_count,
tsu.internal_objects_dealloc_page_count,
tsu.user_objects_alloc_page_count,
tsu.user_objects_dealloc_page_count,
tsu.exec_context_id,
r.status,
r.wait_type,
r.wait_time,
r.cpu_time,
LTRIM(RTRIM(REPLACE(REPLACE(SUBSTRING(t.text, (r.statement_start_offset/2)+1,
((CASE r.statement_end_offset
WHEN -1 THEN DATALENGTH(t.text)
ELSE r.statement_end_offset
END - r.statement_start_offset)/2) + 1), CHAR(10), ' '), CHAR(13), ' '))) AS statement_text,
LTRIM(RTRIM(REPLACE(REPLACE(SUBSTRING(t.text, 0,256), CHAR(10), ' '), CHAR(13), ' '))) AS batch_text
FROM sys.dm_db_task_space_usage tsu
LEFT JOIN sys.dm_exec_requests r
ON tsu.session_id = r.session_id
ON tsu.session_id = r.session_id
CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) t
WHERE (internal_objects_alloc_page_count + internal_objects_dealloc_page_count + user_objects_alloc_page_count + user_objects_dealloc_page_count) !=0
ORDER BY (user_objects_alloc_page_count + internal_objects_alloc_page_count) DESC
OPTION (max_grant_percent = 3, MAXDOP 2)
PRINT ''
WHERE (internal_objects_alloc_page_count + internal_objects_dealloc_page_count + user_objects_alloc_page_count + user_objects_dealloc_page_count) !=0
ORDER BY (user_objects_alloc_page_count + internal_objects_alloc_page_count) DESC
OPTION (max_grant_percent = 3, MAXDOP 2)
PRINT ''
PRINT '-- version store transactions --'
SELECT @runtime AS runtime,
ast.transaction_id,
ast.transaction_sequence_num,
ast.commit_sequence_num,
ast.elapsed_time_seconds,
ast.average_version_chain_traversed,
ast.max_version_chain_traversed,
ast.first_snapshot_sequence_num,
ast.is_snapshot,
ast.session_id,
r.blocking_session_id,
r.status,
r.wait_type,
r.wait_time,
r.cpu_time,
r.total_elapsed_time,
r.granted_query_memory,
r.open_transaction_count,
r.transaction_isolation_level,
LTRIM(RTRIM(REPLACE(REPLACE(SUBSTRING(t.text, (r.statement_start_offset/2)+1,
((CASE r.statement_end_offset
WHEN -1 THEN DATALENGTH(t.text)
ELSE r.statement_end_offset
END - r.statement_start_offset)/2) + 1), CHAR(10), ' '), CHAR(13), ' '))) AS statement_text
FROM sys.dm_tran_active_snapshot_database_transactions ast
PRINT '-- version store transactions --'
SELECT @runtime AS runtime,
ast.transaction_id,
ast.transaction_sequence_num,
ast.commit_sequence_num,
ast.elapsed_time_seconds,
ast.average_version_chain_traversed,
ast.max_version_chain_traversed,
ast.first_snapshot_sequence_num,
ast.is_snapshot,
ast.session_id,
r.blocking_session_id,
r.status,
r.wait_type,
r.wait_time,
r.cpu_time,
r.total_elapsed_time,
r.granted_query_memory,
r.open_transaction_count,
r.transaction_isolation_level,
LTRIM(RTRIM(REPLACE(REPLACE(SUBSTRING(t.text, (r.statement_start_offset/2)+1,
((CASE r.statement_end_offset
WHEN -1 THEN DATALENGTH(t.text)
ELSE r.statement_end_offset
END - r.statement_start_offset)/2) + 1), CHAR(10), ' '), CHAR(13), ' '))) AS statement_text
FROM sys.dm_tran_active_snapshot_database_transactions ast
LEFT JOIN sys.dm_exec_requests r
ON ast.session_id = r.session_id
CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) as t
RAISERROR ('', 0, 1) WITH NOWAIT
PRINT ''
ON ast.session_id = r.session_id
CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) as t
RAISERROR ('', 0, 1) WITH NOWAIT
PRINT ''
PRINT '-- open transactions --'
SELECT @runtime AS runtime,
s_tdt.transaction_id,
s_tdt.database_transaction_state,
s_tdt.database_transaction_type,
s_tdt.database_transaction_log_record_count,
s_tdt.database_transaction_begin_lsn,
s_tdt.database_transaction_last_lsn,
s_tdt.database_transaction_begin_time,
s_tdt.database_transaction_log_bytes_used,
s_tdt.database_transaction_log_bytes_reserved,
s_tdt.database_transaction_log_bytes_reserved_system,
s_tdt.database_transaction_log_bytes_used_system,
s_tst.session_id,
s_tst.is_local,
s_es.login_time,
s_es.last_request_end_time,
CONVERT(VARCHAR(36), DB_NAME (s_tdt.database_id)) AS dbname,
con.most_recent_session_id,
s_es.open_transaction_count,
s_es.status,
SUBSTRING(s_es.host_name, 0, 48) host_name,
SUBSTRING(s_es.program_name,0,48) program_name,
s_es.is_user_process,
s_es.host_process_id,
SUBSTRING(s_es.login_name, 0,48) login_name,
con.client_net_address,
con.net_transport
FROM sys.dm_tran_database_transactions s_tdt
PRINT '-- open transactions --'
SELECT @runtime AS runtime,
s_tdt.transaction_id,
s_tdt.database_transaction_state,
s_tdt.database_transaction_type,
s_tdt.database_transaction_log_record_count,
s_tdt.database_transaction_begin_lsn,
s_tdt.database_transaction_last_lsn,
s_tdt.database_transaction_begin_time,
s_tdt.database_transaction_log_bytes_used,
s_tdt.database_transaction_log_bytes_reserved,
s_tdt.database_transaction_log_bytes_reserved_system,
s_tdt.database_transaction_log_bytes_used_system,
s_tst.session_id,
s_tst.is_local,
s_es.login_time,
s_es.last_request_end_time,
CONVERT(VARCHAR(36), DB_NAME (s_tdt.database_id)) AS dbname,
con.most_recent_session_id,
s_es.open_transaction_count,
s_es.status,
SUBSTRING(s_es.host_name, 0, 48) host_name,
SUBSTRING(s_es.program_name,0,48) program_name,
s_es.is_user_process,
s_es.host_process_id,
SUBSTRING(s_es.login_name, 0,48) login_name,
con.client_net_address,
con.net_transport
FROM sys.dm_tran_database_transactions s_tdt
JOIN sys.dm_tran_session_transactions s_tst
ON s_tst.transaction_id = s_tdt.transaction_id
JOIN sys.dm_exec_sessions AS s_es
ON s_es.session_id = s_tst.session_id
ON s_es.session_id = s_tst.session_id
LEFT OUTER JOIN sys.dm_exec_requests s_er
ON s_er.session_id = s_tst.session_id
LEFT OUTER JOIN sys.dm_exec_connections con
ON con.session_id = s_tst.session_id
OUTER APPLY sys.dm_exec_sql_text(con.most_recent_sql_handle) T
ORDER BY database_transaction_begin_time ASC
OPTION (max_grant_percent = 3, MAXDOP 2)
ON s_er.session_id = s_tst.session_id
LEFT OUTER JOIN sys.dm_exec_connections con
ON con.session_id = s_tst.session_id
OUTER APPLY sys.dm_exec_sql_text(con.most_recent_sql_handle) T
ORDER BY database_transaction_begin_time ASC
OPTION (max_grant_percent = 3, MAXDOP 2)
RAISERROR ('', 0, 1) WITH NOWAIT
PRINT ''
PRINT '-- tempdb usage by objects --'
SELECT TOP 10
@runtime AS runtime,
CONVERT(VARCHAR(16), DB_NAME ()) AS dbname,
DB_ID() AS database_id,
_Objects.schema_id AS schema_id,
Schema_Name(_Objects.schema_id) AS schema_name,
_Objects.object_id AS object_id,
RTrim(_Objects.name) AS table_name,
(~(Cast(_Partitions.index_id AS Bit))) AS is_heap,
SUM(_Partitions.used_page_count) * 8192/1024 used_pages_kb,
SUM(_Partitions.reserved_page_count) * 8192/1024 reserved_pages_kb
FROM sys.objects AS _Objects
INNER JOIN sys.dm_db_partition_stats AS _Partitions
ON (_Objects.object_id = _Partitions.object_id)
WHERE (_Partitions.index_id IN (0, 1))
GROUP BY _Objects.schema_id,
_Objects.object_id,
_Objects.name,
_Partitions.index_id
ORDER BY used_pages_kb DESC
OPTION (max_grant_percent = 3, MAXDOP 2)
PRINT ''
RAISERROR ('', 0, 1) WITH NOWAIT
PRINT ''
PRINT '-- tempdb usage by objects --'
SELECT TOP 10
@runtime AS runtime,
CONVERT(VARCHAR(16), DB_NAME ()) AS dbname,
DB_ID() AS database_id,
_Objects.schema_id AS schema_id,
Schema_Name(_Objects.schema_id) AS schema_name,
_Objects.object_id AS object_id,
RTrim(_Objects.name) AS table_name,
(~(Cast(_Partitions.index_id AS Bit))) AS is_heap,
SUM(_Partitions.used_page_count) * 8192/1024 used_pages_kb,
SUM(_Partitions.reserved_page_count) * 8192/1024 reserved_pages_kb
FROM sys.objects AS _Objects
INNER JOIN sys.dm_db_partition_stats AS _Partitions
ON (_Objects.object_id = _Partitions.object_id)
WHERE (_Partitions.index_id IN (0, 1))
GROUP BY _Objects.schema_id,
_Objects.object_id,
_Objects.name,
_Partitions.index_id
ORDER BY used_pages_kb DESC
OPTION (max_grant_percent = 3, MAXDOP 2)
PRINT ''
PRINT '-- waits-in-tempdb --'
SELECT @runtime AS runtime,
session_id,
start_time,
status,
command,
CONVERT(VARCHAR(36), DB_NAME (database_id)) AS dbname,
blocking_session_id,
wait_type,
wait_time,
last_wait_type,
wait_resource,
open_transaction_count,
cpu_time,
total_elapsed_time,
logical_reads
FROM sys.dm_exec_requests
WHERE wait_resource like '% 2:%'
OPTION (max_grant_percent = 3, MAXDOP 2)
PRINT '-- waits-in-tempdb --'
SELECT @runtime AS runtime,
session_id,
start_time,
status,
command,
CONVERT(VARCHAR(36), DB_NAME (database_id)) AS dbname,
blocking_session_id,
wait_type,
wait_time,
last_wait_type,
wait_resource,
open_transaction_count,
cpu_time,
total_elapsed_time,
logical_reads
FROM sys.dm_exec_requests
WHERE wait_resource like '% 2:%'
OPTION (max_grant_percent = 3, MAXDOP 2)
PRINT ''
IF @sql_major_version >= 15
@ -243,10 +248,278 @@ BEGIN
FROM sys.dm_tran_aborted_transactions
END
RAISERROR ('', 0, 1) WITH NOWAIT
PRINT ''
PRINT '-- sys.dm_tran_active_transactions --'
SELECT [transaction_id],
[name],
[transaction_begin_time],
[transaction_type],
[transaction_uow],
[transaction_state],
[transaction_status],
[transaction_status2],
[dtc_state],
[dtc_status],
[dtc_isolation_level],
[filestream_transaction_id]
FROM sys.dm_tran_active_transactions
RAISERROR ('', 0, 1) WITH NOWAIT
PRINT ''
--in-memory related
IF (@sql_major_version > 11)
BEGIN
DECLARE @database_id INT
DECLARE @dbname SYSNAME
DECLARE @count INT
DECLARE @maxcount INT
DECLARE @sql NVARCHAR(MAX)
CREATE TABLE #dbtable (
id INT IDENTITY (1,1) PRIMARY KEY,
database_id INT,
dbname SYSNAME
)
--database level in-memory dmvs
SELECT IDENTITY(INT,1,1) AS id,
@database_id as database_id ,
@dbname as dbname
INTO #db_inmemory
FROM sys.databases
WHERE 1=0
INSERT INTO #dbtable
SELECT database_id, name FROM sys.databases WHERE state_desc='ONLINE'
SET @count = 1
SET @maxcount = (SELECT MAX(id) FROM #dbtable)
WHILE (@count<=@maxcount)
BEGIN
SELECT @database_id = database_id,
@dbname = dbname
FROM #dbtable
WHERE id = @count
SET @sql = N'USE [' + @dbname + '];
IF EXISTS(SELECT type_desc FROM sys.data_spaces WHERE type_desc = ''MEMORY_OPTIMIZED_DATA_FILEGROUP'')
BEGIN
INSERT INTO #db_inmemory VALUES (' + CONVERT(NVARCHAR(50),@database_id) + ',''' + @dbname +''');
END'
--print @sql
EXEC (@sql)
SET @count = @count + 1
END
PRINT '-- sys.dm_db_xtp_transactions --'
CREATE TABLE #tmp_dm_db_xtp_transactions (
[dbname] SYSNAME NULL,
[node_id] SMALLINT NULL,
[xtp_transaction_id] BIGINT NULL,
[transaction_id] BIGINT NULL,
[session_id] SMALLINT NULL,
[begin_tsn] BIGINT NULL,
[end_tsn] BIGINT NULL,
[state] INT NULL,
[state_desc] NVARCHAR(16) NULL,
[result] INT NULL,
[result_desc] NVARCHAR(24) NULL,
[xtp_parent_transaction_node_id] SMALLINT NULL,
[xtp_parent_transaction_id] BIGINT NULL,
[last_error]INT NULL,
[is_speculative] BIT NULL,
[is_prepared] BIT NULL,
[is_delayed_durability] BIT NULL ,
[memory_address] VARBINARY(8) NULL,
[database_address] VARBINARY(8) NULL,
[thread_id] INT NULL,
[read_set_row_count] INT NULL,
[write_set_row_count] INT NULL,
[scan_set_count] INT NULL,
[savepoint_garbage_count] INT NULL,
[log_bytes_required]BIGINT NULL,
[count_of_allocations] INT NULL,
[allocated_bytes] INT NULL,
[reserved_bytes] INT NULL,
[commit_dependency_count] INT NULL,
[commit_dependency_total_attempt_count] INT NULL,
[scan_area] INT NULL,
[scan_area_desc] NVARCHAR(16) NULL,
[scan_location] INT NULL,
[dependent_1_address] VARBINARY(8) NULL,
[dependent_2_address] VARBINARY(8) NULL,
[dependent_3_address] VARBINARY(8) NULL,
[dependent_4_address] VARBINARY(8) NULL,
[dependent_5_address] VARBINARY(8) NULL,
[dependent_6_address] VARBINARY(8) NULL,
[dependent_7_address] VARBINARY(8) NULL,
[dependent_8_address] VARBINARY(8) NULL
)
SET @count = 1
SET @maxcount = (SELECT MAX(id) FROM #db_inmemory)
WHILE (@count<=@maxcount)
BEGIN
SELECT @database_id = database_id,
@dbname = dbname
FROM #db_inmemory
WHERE id = @count
IF (@sql_major_version >=13 )
BEGIN
SET @sql = N'USE [' + @dbname + '];
INSERT INTO #tmp_dm_db_xtp_transactions
SELECT '''+@dbname+''',
[node_id],
[xtp_transaction_id],
[transaction_id],
[session_id],
[begin_tsn],
[end_tsn],
[state],
[state_desc],
[result],
[result_desc],
[xtp_parent_transaction_node_id],
[xtp_parent_transaction_id],
[last_error],
[is_speculative],
[is_prepared],
[is_delayed_durability],
[memory_address],
[database_address],
[thread_id],
[read_set_row_count],
[write_set_row_count],
[scan_set_count],
[savepoint_garbage_count],
[log_bytes_required],
[count_of_allocations],
[allocated_bytes],
[reserved_bytes],
[commit_dependency_count],
[commit_dependency_total_attempt_count],
[scan_area],
[scan_area_desc],
[scan_location],
[dependent_1_address],
[dependent_2_address],
[dependent_3_address],
[dependent_4_address],
[dependent_5_address],
[dependent_6_address],
[dependent_7_address],
[dependent_8_address]
FROM sys.dm_db_xtp_transactions;'
END
ELSE
BEGIN
SET @sql = N'USE [' + @dbname + '];
INSERT INTO #tmp_dm_db_xtp_transactions
SELECT '''+@dbname+''',
NULL, --[node_id],
[xtp_transaction_id],
[transaction_id],
[session_id],
[begin_tsn],
[end_tsn],
[state],
[state_desc],
[result],
[result_desc],
NULL, --[xtp_parent_transaction_node_id],
NULL, --[xtp_parent_transaction_id],
[last_error],
[is_speculative],
[is_prepared],
[is_delayed_durability],
[memory_address],
[database_address],
[thread_id],
[read_set_row_count],
[write_set_row_count],
[scan_set_count],
[savepoint_garbage_count],
[log_bytes_required],
[count_of_allocations],
[allocated_bytes],
[reserved_bytes],
[commit_dependency_count],
[commit_dependency_total_attempt_count],
[scan_area],
[scan_area_desc],
[scan_location],
[dependent_1_address],
[dependent_2_address],
[dependent_3_address],
[dependent_4_address],
[dependent_5_address],
[dependent_6_address],
[dependent_7_address],
[dependent_8_address]
FROM sys.dm_db_xtp_transactions;'
END
--print @sql
EXEC (@sql)
SET @count = @count + 1
END
SELECT CONVERT (varchar(30), @runtime, 121) as runtime, * FROM #tmp_dm_db_xtp_transactions
RAISERROR ('', 0, 1) WITH NOWAIT
PRINT ''
WAITFOR DELAY '00:01:00'
PRINT '-- sys.dm_xtp_transaction_stats --'
SET @sql = N'SELECT [total_count]
,[read_only_count]
,[total_aborts]
,[system_aborts]
,[validation_failures]
,[dependencies_taken]
,[dependencies_failed]
,[savepoint_create]
,[savepoint_rollbacks]
,[savepoint_refreshes]
,[log_bytes_written]
,[log_IO_count]
,[phantom_scans_started]
,[phantom_scans_retries]
,[phantom_rows_touched]
,[phantom_rows_expiring]
,[phantom_rows_expired]
,[phantom_rows_expired_removed]
,[scans_started]
,[scans_retried]
,[rows_returned]
,[rows_touched]
,[rows_expiring]
,[rows_expired]
,[rows_expired_removed]
,[row_insert_attempts]
,[row_update_attempts]
,[row_delete_attempts]
,[write_conflicts]
,[unique_constraint_violations]'
IF (@sql_major_version >= 13)
BEGIN
SET @sql = @sql + N',[drop_table_memory_attempts]
,[drop_table_memory_failures]'
END
SET @sql = @sql + N'FROM sys.dm_xtp_transaction_stats;
RAISERROR ('''', 0, 1) WITH NOWAIT;'
EXEC (@sql)
END
WAITFOR DELAY '00:01:00'
END
GO

Просмотреть файл

@ -14,7 +14,10 @@ param
[bool] $DoProcmonTest = $false,
[Parameter(Position=4)]
[string] $Scenarios = "All"
[string] $Scenarios = "All",
[Parameter(Position=5)]
[string] $DisableCtrlCasInput = "False"
)
@ -73,77 +76,110 @@ try
[int] $TestCount = 0
$temp_return_val = 0
$return_val = 0
#Run Tests and send results to a summary file
# Individual Scenarios
if ($Scenarios -in ("Basic", "All"))
{
.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "Basic" -SummaryOutputFile $SummaryOutputFilename -SqlNexusPath $SqlNexusPath -SqlNexusDb $SqlNexusDb -LogScoutOutputFolder $LogScoutOutputFolder -RootFolder $root_folder
$temp_return_val = .\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "Basic" -SummaryOutputFile $SummaryOutputFilename -SqlNexusPath $SqlNexusPath -SqlNexusDb $SqlNexusDb -LogScoutOutputFolder $LogScoutOutputFolder -RootFolder $root_folder -DisableCtrlCasInput $DisableCtrlCasInput
#due to PS pipeline, Scenario_Test returns many things in an array.
#We need to get the last element of the array - the return value which is sent out last
$return_val+=$temp_return_val[$temp_return_val.Count-1]
$TestCount++
}
if ($Scenarios -in ("GeneralPerf", "All"))
{
.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "GeneralPerf" -SummaryOutputFile $SummaryOutputFilename -SqlNexusPath $SqlNexusPath -SqlNexusDb $SqlNexusDb -LogScoutOutputFolder $LogScoutOutputFolder -RootFolder $root_folder -RunTSQLLoad $true
$temp_return_val = .\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "GeneralPerf" -SummaryOutputFile $SummaryOutputFilename -SqlNexusPath $SqlNexusPath -SqlNexusDb $SqlNexusDb -LogScoutOutputFolder $LogScoutOutputFolder -RootFolder $root_folder -RunTSQLLoad $true -DisableCtrlCasInput $DisableCtrlCasInput
$return_val+=$temp_return_val[$temp_return_val.Count-1]
$TestCount++
}
if ($Scenarios -in ("DetailedPerf", "All"))
{
.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "DetailedPerf" -SummaryOutputFile $SummaryOutputFilename -SqlNexusPath $SqlNexusPath -SqlNexusDb $SqlNexusDb -LogScoutOutputFolder $LogScoutOutputFolder -RootFolder $root_folder -RunTSQLLoad $true
$temp_return_val = .\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "DetailedPerf" -SummaryOutputFile $SummaryOutputFilename -SqlNexusPath $SqlNexusPath -SqlNexusDb $SqlNexusDb -LogScoutOutputFolder $LogScoutOutputFolder -RootFolder $root_folder -RunTSQLLoad $true -DisableCtrlCasInput $DisableCtrlCasInput
$return_val+=$temp_return_val[$temp_return_val.Count-1]
$TestCount++
}
if ($Scenarios -in ("Replication", "All"))
{
.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "Replication" -SummaryOutputFile $SummaryOutputFilename -SqlNexusPath $SqlNexusPath -SqlNexusDb $SqlNexusDb -LogScoutOutputFolder $LogScoutOutputFolder -RootFolder $root_folder
$temp_return_val =.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "Replication" -SummaryOutputFile $SummaryOutputFilename -SqlNexusPath $SqlNexusPath -SqlNexusDb $SqlNexusDb -LogScoutOutputFolder $LogScoutOutputFolder -RootFolder $root_folder -DisableCtrlCasInput $DisableCtrlCasInput
$return_val+=$temp_return_val[$temp_return_val.Count-1]
$TestCount++
}
if ($Scenarios -in ("AlwaysOn", "All"))
{
.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "AlwaysOn" -SummaryOutputFile $SummaryOutputFilename -SqlNexusPath $SqlNexusPath -SqlNexusDb $SqlNexusDb -LogScoutOutputFolder $LogScoutOutputFolder -RootFolder $root_folder -RunTSQLLoad $true
$temp_return_val =.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "AlwaysOn" -SummaryOutputFile $SummaryOutputFilename -SqlNexusPath $SqlNexusPath -SqlNexusDb $SqlNexusDb -LogScoutOutputFolder $LogScoutOutputFolder -RootFolder $root_folder -RunTSQLLoad $true -DisableCtrlCasInput $DisableCtrlCasInput
$return_val+=$temp_return_val[$temp_return_val.Count-1]
$TestCount++
}
if ($Scenarios -in ("NetworkTrace", "All"))
{
.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "NetworkTrace" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder
$temp_return_val =.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "NetworkTrace" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder -DisableCtrlCasInput $DisableCtrlCasInput
$return_val+=$temp_return_val[$temp_return_val.Count-1]
$TestCount++
}
if ($Scenarios -in ("Memory", "All"))
{
.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "Memory" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder -RunTSQLLoad $true
$temp_return_val =.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "Memory" -SummaryOutputFile $SummaryOutputFilename -SqlNexusPath $SqlNexusPath -SqlNexusDb $SqlNexusDb -LogScoutOutputFolder $LogScoutOutputFolder -RootFolder $root_folder -RunTSQLLoad $true -DisableCtrlCasInput $DisableCtrlCasInput
$return_val+=$temp_return_val[$temp_return_val.Count-1]
$TestCount++
}
if ($Scenarios -in ("Setup", "All"))
{
.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "Setup" -SummaryOutputFile $SummaryOutputFilename -SqlNexusPath $SqlNexusPath -SqlNexusDb $SqlNexusDb -LogScoutOutputFolder $LogScoutOutputFolder -RootFolder $root_folder
$temp_return_val =.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "Setup" -SummaryOutputFile $SummaryOutputFilename -SqlNexusPath $SqlNexusPath -SqlNexusDb $SqlNexusDb -LogScoutOutputFolder $LogScoutOutputFolder -RootFolder $root_folder -DisableCtrlCasInput $DisableCtrlCasInput
$return_val+=$temp_return_val[$temp_return_val.Count-1]
$TestCount++
}
if ($Scenarios -in ("BackupRestore", "All"))
{
.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "BackupRestore" -SummaryOutputFile $SummaryOutputFilename -SqlNexusPath $SqlNexusPath -SqlNexusDb $SqlNexusDb -LogScoutOutputFolder $LogScoutOutputFolder -RootFolder $root_folder
$temp_return_val =.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "BackupRestore" -SummaryOutputFile $SummaryOutputFilename -SqlNexusPath $SqlNexusPath -SqlNexusDb $SqlNexusDb -LogScoutOutputFolder $LogScoutOutputFolder -RootFolder $root_folder -DisableCtrlCasInput $DisableCtrlCasInput
$return_val+=$temp_return_val[$temp_return_val.Count-1]
$TestCount++
}
if ($Scenarios -in ("IO", "All"))
{
.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "IO" -SummaryOutputFile $SummaryOutputFilename -SqlNexusPath $SqlNexusPath -SqlNexusDb $SqlNexusDb -LogScoutOutputFolder $LogScoutOutputFolder -RootFolder $root_folder -RunTSQLLoad $true
$temp_return_val =.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "IO" -SummaryOutputFile $SummaryOutputFilename -SqlNexusPath $SqlNexusPath -SqlNexusDb $SqlNexusDb -LogScoutOutputFolder $LogScoutOutputFolder -RootFolder $root_folder -RunTSQLLoad $true -DisableCtrlCasInput $DisableCtrlCasInput
$return_val+=$temp_return_val[$temp_return_val.Count-1]
$TestCount++
}
if ($Scenarios -in ("LightPerf", "All"))
{
.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "LightPerf" -SummaryOutputFile $SummaryOutputFilename -SqlNexusPath $SqlNexusPath -SqlNexusDb $SqlNexusDb -LogScoutOutputFolder $LogScoutOutputFolder -RootFolder $root_folder -RunTSQLLoad $true
$temp_return_val =.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "LightPerf" -SummaryOutputFile $SummaryOutputFilename -SqlNexusPath $SqlNexusPath -SqlNexusDb $SqlNexusDb -LogScoutOutputFolder $LogScoutOutputFolder -RootFolder $root_folder -RunTSQLLoad $true -DisableCtrlCasInput $DisableCtrlCasInput
$return_val+=$temp_return_val[$temp_return_val.Count-1]
$TestCount++
}
#Process monitor is a bit different
if (($Scenarios -eq "ProcessMonitor") -or ($Scenarios -eq "All" -and $DoProcmonTest -eq $true))
{
.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "ProcessMonitor" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder
$temp_return_val =.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "ProcessMonitor" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder -DisableCtrlCasInput $DisableCtrlCasInput
$return_val+=$temp_return_val[$temp_return_val.Count-1]
$TestCount++
}
if ($Scenarios -in ("ServiceBrokerDBMail", "All"))
{
$temp_return_val =.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "ServiceBrokerDBMail" -SummaryOutputFile $SummaryOutputFilename -SqlNexusPath $SqlNexusPath -SqlNexusDb $SqlNexusDb -LogScoutOutputFolder $LogScoutOutputFolder -RootFolder $root_folder -RunTSQLLoad $true -DisableCtrlCasInput $DisableCtrlCasInput
$return_val+=$temp_return_val[$temp_return_val.Count-1]
$TestCount++
}
if ($Scenarios -in ("NeverEndingQuery", "All"))
{
$temp_return_val =.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "NeverEndingQuery" -SummaryOutputFile $SummaryOutputFilename -SqlNexusPath $SqlNexusPath -SqlNexusDb $SqlNexusDb -LogScoutOutputFolder $LogScoutOutputFolder -RootFolder $root_folder -RunTSQLLoad $true -DisableCtrlCasInput $DisableCtrlCasInput
$return_val+=$temp_return_val[$temp_return_val.Count-1]
$TestCount++
}
#combine Basic with a Network others
if ($Scenarios -in ("Basic+NetworkTrace", "All"))
{
.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "Basic+NetworkTrace" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder
$temp_return_val =.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "Basic+NetworkTrace" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder -DisableCtrlCasInput $DisableCtrlCasInput
$return_val+=$temp_return_val[$temp_return_val.Count-1]
$TestCount++
}
@ -151,137 +187,180 @@ try
# combine scenario with NoBasic
if ($Scenarios -in ("Basic+NoBasic", "All"))
{
.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "Basic+NoBasic" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder
$temp_return_val =.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "Basic+NoBasic" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder -DisableCtrlCasInput $DisableCtrlCasInput
$return_val+=$temp_return_val[$temp_return_val.Count-1]
$TestCount++
}
if ($Scenarios -in ("GeneralPerf+NoBasic", "All"))
{
.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "GeneralPerf+NoBasic" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder -RunTSQLLoad $true
$temp_return_val =.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "GeneralPerf+NoBasic" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder -RunTSQLLoad $true -DisableCtrlCasInput $DisableCtrlCasInput
$return_val+=$temp_return_val[$temp_return_val.Count-1]
$TestCount++
}
if ($Scenarios -in ("DetailedPerf+NoBasic", "All"))
{
.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "DetailedPerf+NoBasic" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder -RunTSQLLoad $true
$temp_return_val =.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "DetailedPerf+NoBasic" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder -RunTSQLLoad $true -DisableCtrlCasInput $DisableCtrlCasInput
$return_val+=$temp_return_val[$temp_return_val.Count-1]
$TestCount++
}
if ($Scenarios -in ("Replication+NoBasic", "All"))
{
.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "Replication+NoBasic" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder
$temp_return_val = .\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "Replication+NoBasic" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder -DisableCtrlCasInput $DisableCtrlCasInput
$return_val+=$temp_return_val[$temp_return_val.Count-1]
$TestCount++
}
if ($Scenarios -in ("AlwaysOn+NoBasic", "All"))
{
.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "AlwaysOn+NoBasic" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder -RunTSQLLoad $true
$temp_return_val = .\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "AlwaysOn+NoBasic" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder -RunTSQLLoad $true -DisableCtrlCasInput $DisableCtrlCasInput
$return_val+=$temp_return_val[$temp_return_val.Count-1]
$TestCount++
}
if ($Scenarios -in ("Memory+NoBasic", "All"))
{
.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "Memory+NoBasic" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder -RunTSQLLoad $true
$temp_return_val = .\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "Memory+NoBasic" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder -RunTSQLLoad $true -DisableCtrlCasInput $DisableCtrlCasInput
$return_val+=$temp_return_val[$temp_return_val.Count-1]
$TestCount++
}
if ($Scenarios -in ("Setup+NoBasic", "All"))
{
.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "Setup+NoBasic" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder
$temp_return_val = .\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "Setup+NoBasic" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder -DisableCtrlCasInput $DisableCtrlCasInput
$return_val+=$temp_return_val[$temp_return_val.Count-1]
$TestCount++
}
if ($Scenarios -in ("BackupRestore+NoBasic", "All"))
{
.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "BackupRestore+NoBasic" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder
$temp_return_val = .\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "BackupRestore+NoBasic" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder -DisableCtrlCasInput $DisableCtrlCasInput
$return_val+=$temp_return_val[$temp_return_val.Count-1]
$TestCount++
}
if ($Scenarios -in ("IO+NoBasic", "All"))
{
.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "IO+NoBasic" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder -RunTSQLLoad $true
$temp_return_val = .\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "IO+NoBasic" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder -RunTSQLLoad $true -DisableCtrlCasInput $DisableCtrlCasInput
$return_val+=$temp_return_val[$temp_return_val.Count-1]
$TestCount++
}
if ($Scenarios -in ("LightPerf+NoBasic", "All"))
{
.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "LightPerf+NoBasic" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder -RunTSQLLoad $true
$temp_return_val = .\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "LightPerf+NoBasic" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder -RunTSQLLoad $true -DisableCtrlCasInput $DisableCtrlCasInput
$return_val+=$temp_return_val[$temp_return_val.Count-1]
$TestCount++
}
# common combination scenarios
if ($Scenarios -in ("GeneralPerf+Replication", "All"))
{
.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "GeneralPerf+Replication" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder -RunTSQLLoad $true
$temp_return_val = .\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "GeneralPerf+Replication" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder -RunTSQLLoad $true -DisableCtrlCasInput $DisableCtrlCasInput
$return_val+=$temp_return_val[$temp_return_val.Count-1][$temp_return_val.Count-1]
$TestCount++
}
if ($Scenarios -in ("GeneralPerf+AlwaysOn", "All"))
{
.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "GeneralPerf+AlwaysOn" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder -RunTSQLLoad $true
$temp_return_val = .\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "GeneralPerf+AlwaysOn" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder -RunTSQLLoad $true -DisableCtrlCasInput $DisableCtrlCasInput
$return_val+=$temp_return_val[$temp_return_val.Count-1][$temp_return_val.Count-1]
$TestCount++
}
if ($Scenarios -in ("GeneralPerf+IO", "All"))
{
.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "GeneralPerf+IO" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder -RunTSQLLoad $true
$temp_return_val = .\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "GeneralPerf+IO" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder -RunTSQLLoad $true -DisableCtrlCasInput $DisableCtrlCasInput
$return_val+=$temp_return_val[$temp_return_val.Count-1][$temp_return_val.Count-1]
$TestCount++
}
if ($Scenarios -in ("GeneralPerf+NetworkTrace", "All"))
{
.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "GeneralPerf+NetworkTrace" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder -RunTSQLLoad $true
$temp_return_val = .\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "GeneralPerf+NetworkTrace" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder -RunTSQLLoad $true -DisableCtrlCasInput $DisableCtrlCasInput
$return_val+=$temp_return_val[$temp_return_val.Count-1][$temp_return_val.Count-1]
$TestCount++
}
if ($Scenarios -in ("DetailedPerf+AlwaysOn", "All"))
{
.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "DetailedPerf+AlwaysOn" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder -RunTSQLLoad $true
$temp_return_val = .\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "DetailedPerf+AlwaysOn" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder -RunTSQLLoad $true -DisableCtrlCasInput $DisableCtrlCasInput
$return_val+=$temp_return_val[$temp_return_val.Count-1][$temp_return_val.Count-1]
$TestCount++
}
if ($Scenarios -in ("DetailedPerf+IO", "All"))
{
.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "DetailedPerf+IO" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder -RunTSQLLoad $true
$temp_return_val = .\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "DetailedPerf+IO" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder -RunTSQLLoad $true -DisableCtrlCasInput $DisableCtrlCasInput
$return_val+=$temp_return_val[$temp_return_val.Count-1][$temp_return_val.Count-1]
$TestCount++
}
if ($Scenarios -in ("DetailedPerf+NetworkTrace", "All"))
{
.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "DetailedPerf+NetworkTrace" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder -RunTSQLLoad $true
$temp_return_val = .\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "DetailedPerf+NetworkTrace" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder -RunTSQLLoad $true -DisableCtrlCasInput $DisableCtrlCasInput
$return_val+=$temp_return_val[$temp_return_val.Count-1]
$TestCount++
}
if ($Scenarios -in ("LightPerf+AlwaysOn", "All"))
{
.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "LightPerf+AlwaysOn" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder -RunTSQLLoad $true
$temp_return_val = .\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "LightPerf+AlwaysOn" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder -RunTSQLLoad $true -DisableCtrlCasInput $DisableCtrlCasInput
$return_val+=$temp_return_val[$temp_return_val.Count-1]
$TestCount++
}
if ($Scenarios -in ("LightPerf+IO", "All"))
{
.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "LightPerf+IO" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder -RunTSQLLoad $true
$temp_return_val = .\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "LightPerf+IO" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder -RunTSQLLoad $true -DisableCtrlCasInput $DisableCtrlCasInput
$return_val+=$temp_return_val[$temp_return_val.Count-1]
$TestCount++
}
if ($Scenarios -in ("LightPerf+BackupRestore", "All"))
{
.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "LightPerf+BackupRestore" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder -RunTSQLLoad $true
$temp_return_val = .\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "LightPerf+BackupRestore" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder -RunTSQLLoad $true -DisableCtrlCasInput $DisableCtrlCasInput
$return_val+=$temp_return_val[$temp_return_val.Count-1]
$TestCount++
}
if ($Scenarios -in ("LightPerf+Memory", "All"))
{
.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "LightPerf+Memory" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder -RunTSQLLoad $true
$temp_return_val = .\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "LightPerf+Memory" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder -RunTSQLLoad $true -DisableCtrlCasInput $DisableCtrlCasInput
$return_val+=$temp_return_val[$temp_return_val.Count-1]
$TestCount++
}
if ($Scenarios -in ("LightPerf+NetworkTrace", "All"))
{
.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "LightPerf+NetworkTrace" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder -RunTSQLLoad $true
$temp_return_val = .\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "LightPerf+NetworkTrace" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder -RunTSQLLoad $true -DisableCtrlCasInput $DisableCtrlCasInput
$return_val+=$temp_return_val[$temp_return_val.Count-1]
$TestCount++
}
if ($Scenarios -in ("ServiceBrokerDBMail+GeneralPerf", "All"))
{
$temp_return_val =.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "ServiceBrokerDBMail+GeneralPerf" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder -RunTSQLLoad $true -DisableCtrlCasInput $DisableCtrlCasInput
$return_val+=$temp_return_val[$temp_return_val.Count-1]
$TestCount++
}
if ($Scenarios -in ("NeverEndingQuery+GeneralPerf", "All"))
{
$temp_return_val =.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "NeverEndingQuery+GeneralPerf" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder -RunTSQLLoad $true -DisableCtrlCasInput $DisableCtrlCasInput
$return_val+=$temp_return_val[$temp_return_val.Count-1]
$TestCount++
}
#Procmon scenario is a bit different needs the extra parameter $DoProcmonTest
if (($Scenarios -eq "ProcessMonitor+Setup") -or ( $Scenarios -eq "All" -and $DoProcmonTest -eq $true))
{
.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "ProcessMonitor+Setup" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder
$temp_return_val = .\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "ProcessMonitor+Setup" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder -DisableCtrlCasInput $DisableCtrlCasInput
$return_val+=$temp_return_val[$temp_return_val.Count-1]
$TestCount++
}
if ($Scenarios -eq ("All"))
{
# scenarios that don't make sense
.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "GeneralPerf+DetailedPerf" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder
.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "GeneralPerf+LightPerf" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder
.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "DetailedPerf+LightPerf" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder
$temp_return_val = .\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "GeneralPerf+DetailedPerf" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder -DisableCtrlCasInput $DisableCtrlCasInput
$return_val+=$temp_return_val[$temp_return_val.Count-1]
$temp_return_val = .\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "GeneralPerf+LightPerf" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder -DisableCtrlCasInput $DisableCtrlCasInput
$return_val+=$temp_return_val[$temp_return_val.Count-1]
$temp_return_val = .\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "DetailedPerf+LightPerf" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder -DisableCtrlCasInput $DisableCtrlCasInput
$return_val+=$temp_return_val[$temp_return_val.Count-1]
#stress tests
.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "DetailedPerf+AlwaysOn+Replication+NetworkTrace+Memory+Setup+BackupRestore+IO" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder
.\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "Basic+GeneralPerf+DetailedPerf+AlwaysOn+Replication+NetworkTrace+Memory+Setup+BackupRestore+IO+LightPerf" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder
$temp_return_val = .\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "DetailedPerf+AlwaysOn+Replication+NetworkTrace+Memory+Setup+BackupRestore+IO" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder -DisableCtrlCasInput $DisableCtrlCasInput
$return_val+=$temp_return_val[$temp_return_val.Count-1]
$temp_return_val = .\Scenarios_Test.ps1 -ServerName $ServerName -Scenarios "Basic+GeneralPerf+DetailedPerf+AlwaysOn+Replication+NetworkTrace+Memory+Setup+BackupRestore+IO+LightPerf" -SummaryOutputFile $SummaryOutputFilename -RootFolder $root_folder -DisableCtrlCasInput $DisableCtrlCasInput
$return_val+=$temp_return_val[$temp_return_val.Count-1]
$TestCount = $TestCount + 5
}
@ -289,12 +368,27 @@ try
# append test count to Summary file
Write-Output "********************************************************************" |Out-File $SummaryOutputFilename -Append
Write-Output "Executed a total of $TestCount test(s)." |Out-File $SummaryOutputFilename -Append
# append overall test status to Summary file
if ($return_val -eq 0)
{
Write-Output "OVERALL STATUS: All tests passed." |Out-File $SummaryOutputFilename -Append
}
else
{
Write-Output "OVERALL STATUS: One or more tests failed." |Out-File $SummaryOutputFilename -Append
}
#print the Summary.txt file in console
Get-Content $SummaryOutputFilename
#Launch the Summary.txt file for review
Start-Process $SummaryOutputFilename
#return the value of the last test
#use exit so parent can handle the error in cmd prompt (%errorlevel%) or powershell ($LASTEXITCODE)
# if ($return_val -ne 0) then the last test failed
exit $return_val
}
catch {
@ -303,5 +397,5 @@ catch {
$error_offset = $PSItem.InvocationInfo.OffsetInLine
$error_script = $PSItem.InvocationInfo.ScriptName
Write-LogError "Function '$($MyInvocation.MyCommand)' failed with error: $error_msg (line: $error_linenum, offset: $error_offset, file: $error_script)"
exit 999
}

Просмотреть файл

@ -47,6 +47,9 @@ $global:DetailFile = ""
[System.Collections.ArrayList]$global:IOFiles = New-Object -TypeName System.Collections.ArrayList
[System.Collections.ArrayList]$global:LightPerfFiles = New-Object -TypeName System.Collections.ArrayList
[System.Collections.ArrayList]$global:ProcessMonitorFiles = New-Object -TypeName System.Collections.ArrayList
[System.Collections.ArrayList]$global:ServiceBrokerDbMailFiles = New-Object -TypeName System.Collections.ArrayList
[System.Collections.ArrayList]$global:NeverEndingQueryFiles = New-Object -TypeName System.Collections.ArrayList
function CopyArray([System.Collections.ArrayList]$Source, [System.Collections.ArrayList]$Destination)
{
@ -58,7 +61,7 @@ function CopyArray([System.Collections.ArrayList]$Source, [System.Collections.Ar
#Function for inclusions to search the logs (debug and regular) for a string and add to array if found as we expect the file to be written.
#Function for inclusions and exclusions to search the logs (debug and regular) for a string and add to array if found as we expect the file to be written.
function ModifyArray()
{
param
@ -72,50 +75,46 @@ function ModifyArray()
[Parameter(Position=2, Mandatory=$true)]
[System.Collections.ArrayList] $ArrayToEdit,
[Parameter(Position=3, Mandatory=$true)]
[Parameter(Position=3, Mandatory=$false)]
[string] $ReferencedLog
)
if ($ActionType -eq 'Add')
{
#Check the default log first as there less records than debug log.
if (Select-String -Path $global:sqllogscout_latest_output_internal_logpath -Pattern $TextToFind)
{
[void]$ArrayToEdit.Add($ReferencedLog)
}
#If we didn't find in default log, then check debug log for the provided string.
elseif (Select-String -Path $global:sqllogscout_latest_output_internal_debuglogpath -Pattern $TextToFind)
[Boolean] $fTextFound = (Select-String -Path $global:sqllogscout_latest_output_internal_logpath -Pattern $TextToFind) -OR
(Select-String -Path $global:sqllogscout_latest_output_internal_debuglogpath -Pattern $TextToFind)
if ($fTextFound)
{
if ($ActionType -eq 'Add')
{
[void]$ArrayToEdit.Add($ReferencedLog)
}
}
WriteToConsoleAndFile -Message "Adding value '$ReferencedLog' to array"
elseif ($ActionType -eq 'Remove')
{
#Check the default log first as there less records than debug log.
if (Select-String -Path $global:sqllogscout_latest_output_internal_logpath -Pattern $TextToFind)
}
elseif ($ActionType -eq 'Remove')
{
[void]$ArrayToEdit.Remove($ReferencedLog)
}
#If we didn't find in default log, then check debug log for the provided string.
elseif (Select-String -Path $global:sqllogscout_latest_output_internal_debuglogpath -Pattern $TextToFind)
[void]$ArrayToEdit.Remove($ReferencedLog)
WriteToConsoleAndFile -Message "Removing value '$ReferencedLog' from array"
} elseif ($ActionType -eq "Clear")
{
[void]$ArrayToEdit.Remove($ReferencedLog)
[void]$ArrayToEdit.Clear()
WriteToConsoleAndFile -Message "Removing all values from array"
}
#We didn't find the provided text so don't add to array. We don't expect the file.
else
{
WriteToConsoleAndFile -Message "Improper use of ModifyArray(). Value passed: $ActionType" -ForegroundColor Red
}
}
#We didn't find the provided text so don't add to array. We don't expect the file.
else
{
WriteToConsoleAndFile -Message "Improper use of ModifyArray(). Value passed: $ModifyArray" -ForegroundColor Red
}
}
function BuildBasicFileArray([bool]$IsNoBasic)
{
$global:BasicFiles =
@ -126,7 +125,7 @@ function BuildBasicFileArray([bool]$IsNoBasic)
'RunningDrivers.csv',
'RunningDrivers.txt',
'SystemInfo_Summary.out',
'MiscPssdiagInfo.out',
'MiscDiagInfo.out',
'TaskListServices.out',
'TaskListVerbose.out',
'PowerPlan.out',
@ -143,13 +142,21 @@ function BuildBasicFileArray([bool]$IsNoBasic)
'Perfmon.out',
'DNSClientInfo.out',
'IPConfig.out',
'NetTCPandUDPConnections.out'
'NetTCPandUDPConnections.out',
'SQL_AzureVM_Information.out',
'Environment_Variables.out',
'azcmagent-logs'
)
# inclusions and exclusions to the array
ModifyArray -ActionType "Add" -TextToFind "This is a Windows Cluster for sure!" -ArrayToEdit $global:BasicFiles -ReferencedLog "_SQLDIAG"
ModifyArray -ActionType "Remove" -TextToFind "Azcmagent not found" -ArrayToEdit $global:BasicFiles -ReferencedLog "azcmagent-logs"
ModifyArray -ActionType "Remove" -TextToFind "Will not collect SQLAssessmentAPI" -ArrayToEdit $global:BasicFiles -ReferencedLog "SQLAssessmentAPI"
ModifyArray -ActionType "Remove" -TextToFind "No SQLAgent log files found" -ArrayToEdit $global:BasicFiles -ReferencedLog "SQLAGENT"
ModifyArray -ActionType "Remove" -TextToFind "SQL_AzureVM_Information will not be collected" -ArrayToEdit $global:BasicFiles -ReferencedLog "SQL_AzureVM_Information.out"
ModifyArray -ActionType "Add" -TextToFind "memory dumps \(max count limit of 20\), from the past 2 months, of size < 100 MB" -ArrayToEdit $global:BasicFiles -ReferencedLog ".mdmp"
ModifyArray -ActionType "Add" -TextToFind "memory dumps \(max count limit of 20\), from the past 2 months, of size < 100 MB" -ArrayToEdit $global:BasicFiles -ReferencedLog "SQLDUMPER_ERRORLOG.log"
ModifyArray -ActionType "Clear" -TextToFind "NeverEndingQuery Exit without collection" -ArrayToEdit $global:BasicFiles
#calculate count of expected files
$ExpectedFiles = $global:BasicFiles
@ -167,10 +174,9 @@ function BuildGeneralPerfFileArray([bool]$IsNoBasic)
'HighCPU_perfstats.out',
'PerfStats.out',
'PerfStatsSnapshotStartup.out',
'Query Store.out',
'QueryStore.out',
'TempDB_and_Tran_Analysis.out',
'linked_server_config.out',
'SSB_diag.out'
'PerfStatsSnapshotShutdown.out',
'Top_CPU_QueryPlansXml_Shutdown_'
)
@ -201,10 +207,9 @@ function BuildDetailedPerfFileArray([bool]$IsNoBasic)
'HighCPU_perfstats.out',
'PerfStats.out',
'PerfStatsSnapshotStartup.out',
'Query Store.out',
'QueryStore.out',
'TempDB_and_Tran_Analysis.out',
'linked_server_config.out',
'SSB_diag.out'
'PerfStatsSnapshotShutdown.out',
'Top_CPU_QueryPlansXml_Shutdown_'
)
@ -272,7 +277,10 @@ function BuildAlwaysOnFileArray([bool]$IsNoBasic)
# inclusions and exclusions to the array
ModifyArray -ActionType "Remove" -TextToFind "AlwaysOn_Data_Movement Xevents is not supported on SQL Server version" -ArrayToEdit $global:AlwaysOnFiles -ReferencedLog "AlwaysOn_Data_Movement_target"
ModifyArray -ActionType "Remove" -TextToFind "This is Not a Windows Cluster!" -ArrayToEdit $global:AlwaysOnFiles -ReferencedLog "cluster.log"
ModifyArray -ActionType "Remove" -TextToFind "HADR is off, skipping data movement and AG Topology" -ArrayToEdit $global:AlwaysOnFiles -ReferencedLog "GetAGTopology.xml"
ModifyArray -ActionType "Remove" -TextToFind "HADR is off, skipping data movement and AG Topology" -ArrayToEdit $global:AlwaysOnFiles -ReferencedLog "AlwaysOn_Data_Movement_target"
ModifyArray -ActionType "Remove" -TextToFind "HADR is off, skipping data movement and AG Topology" -ArrayToEdit $global:AlwaysOnFiles -ReferencedLog "xevent_LogScout_target"
#calculate count of expected files
$ExpectedFiles = $global:AlwaysOnFiles
return $ExpectedFiles
@ -480,10 +488,9 @@ function BuildLightPerfFileArray([bool]$IsNoBasic)
'HighCPU_perfstats.out',
'PerfStats.out',
'PerfStatsSnapshotStartup.out',
'Query Store.out',
'QueryStore.out',
'TempDB_and_Tran_Analysis.out',
'linked_server_config.out',
'SSB_diag.out',
'PerfStatsSnapshotShutdown.out',
'Top_CPU_QueryPlansXml_Shutdown_'
)
@ -521,6 +528,44 @@ function BuildProcessMonitorFileArray([bool]$IsNoBasic)
return $ExpectedFiles
}
function BuildNeverEndingQueryFileArray([bool]$IsNoBasic)
{
$global:NeverEndingQueryFiles =
@(
'NeverEndingQuery_perfstats.out',
'NeverEnding_HighCPU_QueryPlansXml_',
'NeverEnding_statistics_QueryPlansXml_'
)
if ($true -ne $IsNoBasic)
{
#add the basic array files
CopyArray -Source $global:BasicFiles -Destination $global:NeverEndingQueryFiles
}
ModifyArray -ActionType "Clear" -TextToFind "NeverEndingQuery Exit without collection" -ArrayToEdit $global:NeverEndingQueryFiles
return $global:NeverEndingQueryFiles
}
function BuildServiceBrokerDbMailFileArray([bool]$IsNoBasic)
{
$global:ServiceBrokerDbMailFiles =
@(
'Perfmon.out',
'SSB_DbMail_Diag.out',
'xevent_LogScout_target'
)
#network trace does not collect basic scenario logs with it
# inclusions and exclusions to the array
#...
#calculate count of expected files
$ExpectedFiles = $global:ServiceBrokerDbMailFiles
return $ExpectedFiles
}
function WriteToSummaryFile ([string]$SummaryOutputString)
{
if ([string]::IsNullOrWhiteSpace($SummaryOutputFile) -ne $true)
@ -605,6 +650,8 @@ function CreateTestResultsFile ([string[]]$ScenarioArray)
"IO" {$fileScenString +="IO"}
"LightPerf" {$fileScenString +="LPf"}
"ProcessMonitor"{$fileScenString +="PrM"}
"ServiceBrokerDBMail"{$fileScenString +="Ssb"}
"NeverEndingQuery" {$fileScenString +="NEQ"}
}
$fileScenString +="_"
@ -621,30 +668,55 @@ function CreateTestResultsFile ([string[]]$ScenarioArray)
$FileName = "FileValidation_" + $fileScenString + (Get-Date -Format "MMddyyyyHHmmss").ToString() + ".txt"
$global:DetailFile = $global:sqllogscout_testing_infrastructure_output_folder + "\" + $FileName
Write-Host "Creating file validation log in folder '$global:DetailFile'"
New-Item -ItemType File -Path $global:sqllogscout_testing_infrastructure_output_folder -Name $FileName | Out-Null
}
}
function CreateLogFilesMissingLog
function Set-TestInfraOutputFolder()
{
$PathToFileMissingLogFile = $global:sqllogscout_testing_infrastructure_output_folder + 'LogFileMissing.LOG'
$present_directory = Convert-Path -Path "." #this gets the current directory called \TestingInfrastructure
# this creates the LogFileMissing.log if output and/or internal folders/files are missing
#create the testing infrastructure output folder
$folder = New-Item -Path $present_directory -Name "Output" -ItemType Directory -Force
$global:sqllogscout_testing_infrastructure_output_folder = $folder.FullName
#create the LogFileMissing.log if output and/or internal folders/files are missing
$PathToFileMissingLogFile = $global:sqllogscout_testing_infrastructure_output_folder + '\LogScoutFolderOrFileMissing.LOG'
# get the latest output folder that contains SQL LogScout logs
$latest = Get-ChildItem -Path $global:sqllogscout_root_directory -Filter "output*" | Sort-Object LastWriteTime -Descending | Select-Object -First 1
#if no output folder is found, then we cannot continue
if ([String]::IsNullOrWhiteSpace($latest))
{
Write-Host "No 'output*' folder(s) found'. Cannot continue" -ForegroundColor Red
Write-Output "No 'output*' folder(s) found'. Cannot continue" | Out-File -FilePath $PathToFileMissingLogFile -Append
return $false
}
#set the path to the latest output folder
$global:sqllogscout_latest_output_folder = ($global:sqllogscout_root_directory + "\"+ $latest + "\")
#check if the \output folder exists
if (!(Test-Path -Path $global:sqllogscout_latest_output_folder ))
{
$OutputFolderCheckLogMessage = "Files are missing or folder " + $global:sqllogscout_latest_output_folder + " does not exist"
$OutputFolderCheckLogMessage = "Folder '" + $global:sqllogscout_latest_output_folder + "' does not exist"
$OutputFolderCheckLogMessage = $OutputFolderCheckLogMessage.replace("`n", " ")
Write-Host $OutputFolderCheckLogMessage -ForegroundColor Red
Write-Host $OutputFolderCheckLogMessage -ForegroundColor Red
Write-Output $OutputFolderCheckLogMessage | Out-File -FilePath $PathToFileMissingLogFile -Append
return $false
}
#check if the \internal folder exists
$global:sqllogscout_latest_internal_folder = ($global:sqllogscout_latest_output_folder + "internal\")
if (!(Test-Path -Path $global:sqllogscout_latest_internal_folder ))
{
$OutputInternalFolderCheckLogMessage = "Files are missing or folder " + $global:sqllogscout_latest_internal_folder + " does not exist"
$OutputInternalFolderCheckLogMessage = "Folder '" + $global:sqllogscout_latest_internal_folder + "' does not exist"
$OutputInternalFolderCheckLogMessage = $OutputInternalFolderCheckLogMessage.replace("`n", " ")
Write-Host $OutputInternalFolderCheckLogMessage -ForegroundColor Red
@ -653,22 +725,11 @@ function CreateLogFilesMissingLog
return $false
}
return $true
}
function Set-TestInfraOutputFolder()
{
# get the latest output folder that contains SQL LogScout logs
$latest = Get-ChildItem -Path $global:sqllogscout_root_directory -Filter "output*" | Sort-Object LastWriteTime -Descending | Select-Object -First 1
$global:sqllogscout_latest_output_folder = ($global:sqllogscout_root_directory + "\"+ $latest + "\")
$global:sqllogscout_latest_internal_folder = ($global:sqllogscout_latest_output_folder + "internal\")
#get the path to the latest SQL LogScout log and debug log files
$global:sqllogscout_latest_output_internal_logpath = ($global:sqllogscout_latest_internal_folder + $global:sqllogscout_log)
$global:sqllogscout_latest_output_internal_debuglogpath = ($global:sqllogscout_latest_internal_folder + $global:sqllogscoutdebug_log)
$present_directory = Convert-Path -Path "." #this gets the current directory called \TestingInfrastructure
#create the testing infrastructure output folder
$folder = New-Item -Path $present_directory -Name "Output" -ItemType Directory -Force
$global:sqllogscout_testing_infrastructure_output_folder = $folder.FullName
return $true
}
#--------------------------------------------------------Scenario check Start ------------------------------------------------------------
@ -676,6 +737,7 @@ function Set-TestInfraOutputFolder()
function FileCountAndFileTypeValidation([string]$scenario_string, [bool]$IsNoBasic)
{
$summary_out_string = ""
$return_val = $true
try
{
@ -756,6 +818,16 @@ function FileCountAndFileTypeValidation([string]$scenario_string, [bool]$IsNoBas
$ExpectedFiles = BuildProcessMonitorFileArray -IsNoBasic $IsNoBasic
$ExpectedFileCount = $global:ProcessMonitorFiles.Count
}
"ServiceBrokerDbMail"
{
$ExpectedFiles = BuildServiceBrokerDbMailFileArray -IsNoBasic $IsNoBasic
$ExpectedFileCount = $global:ServiceBrokerDbMailFiles.Count
}
"NeverEndingQuery"
{
$ExpectedFiles = BuildNeverEndingQueryFileArray -IsNoBasic $IsNoBasic
$ExpectedFileCount = $global:NeverEndingQueryFiles.Count
}
}
@ -814,6 +886,8 @@ function FileCountAndFileTypeValidation([string]$scenario_string, [bool]$IsNoBas
WriteToConsoleAndFile -Message ("Status: FAILED") -ForegroundColor Red
$summary_out_string = ($summary_out_string + " "*(60 - $summary_out_string.Length) +"FAILED!!! (See '$global:DetailFile' for more details)")
$return_val = $false
}
else
{
@ -823,6 +897,8 @@ function FileCountAndFileTypeValidation([string]$scenario_string, [bool]$IsNoBas
WriteToConsoleAndFile -Message ("Summary: All expected log files for scenario '$scenario_string' are present in your latest output folder!!")
$summary_out_string = ($summary_out_string + " "*(60 - $summary_out_string.Length) +"SUCCESS")
$return_val = $true
}
#write to Summary.txt if ConsistenQualityTests has been executed
@ -847,6 +923,11 @@ function FileCountAndFileTypeValidation([string]$scenario_string, [bool]$IsNoBas
WriteToConsoleAndFile -Message $msg
WriteToConsoleAndFile -Message "`n************************************************************************************************`n"
#send out success of failure message: true (success) or false (failed)
#if the expected file count is not equal to the actual file count, then fail
#if the expected file count is equal to the actual file count, then pass
return $return_val
} # end of try
catch
{
@ -856,7 +937,7 @@ function FileCountAndFileTypeValidation([string]$scenario_string, [bool]$IsNoBas
$error_linenum = $PSItem.InvocationInfo.ScriptLineNumber
$error_offset = $PSItem.InvocationInfo.OffsetInLine
Write-LogError "Function $mycommand failed with error: $error_msg (line: $error_linenum, $error_offset)"
return
return $false
}
}
@ -865,9 +946,14 @@ function FileCountAndFileTypeValidation([string]$scenario_string, [bool]$IsNoBas
function main()
{
$ret = $true
# Call Function to set global variables that represent the various SQLLogScout output folder structures like debug, internal, output, testinginfra etc.
Set-TestInfraOutputFolder
if (!(Set-TestInfraOutputFolder))
{
Write-Host "Cannot continue test due to missing folders. Exiting..." -ForegroundColor Red
return
}
#if SQL LogScout has been run longer than 2 days ago, prompt to re-run
$currentDate = [DateTime]::Now.AddDays(-2)
@ -875,11 +961,6 @@ function main()
try
{
#in case SQLLogScout collected logs are missing
if (!(CreateLogFilesMissingLog))
{
return
}
# get the latest sqllogscoutlog file and full path
$sqllogscoutlog = Get-Childitem -Path $global:sqllogscout_latest_output_internal_logpath -Filter $global:sqllogscout_log
@ -930,26 +1011,28 @@ function main()
}
#validate the file
FileCountAndFileTypeValidation -scenario_string $str_scn -IsNoBasic $nobasic
$ret = FileCountAndFileTypeValidation -scenario_string $str_scn -IsNoBasic $nobasic
}
}
else
{
WriteToConsoleAndFile -Message "No valid Scenario found to process. Exiting"
return
return $false
}
}
else
{
"The collected files are old......." | Out-File -FilePath $global:DetailFile -Append
Write-Host 'The collected files are old. Please re-run the SQL LogScout and collect more recent logs.......' -ForegroundColor Red
return $false
}
Write-Host "`n`n"
$msg = "Testing has been completed, the reports are at: " + $global:sqllogscout_testing_infrastructure_output_folder
Write-Host $msg
#send out success of failure message: true (success) or false (failed) that came from FileCountAndFileTypeValidation
return $ret
}
catch
@ -959,7 +1042,7 @@ function main()
Write-Host $_.Exception.Message
$error_linenum = $PSItem.InvocationInfo.ScriptLineNumber
$error_offset = $PSItem.InvocationInfo.OffsetInLine
Write-LogError "Function $mycommand failed with error: $error_msg (line: $error_linenum, $error_offset)"
Write-LogError "Function '$mycommand' in 'FileCountAndTypeValidation.ps1' failed with error: $error_msg (line: $error_linenum, $error_offset)"
}
}

Просмотреть файл

@ -0,0 +1,263 @@
[System.Diagnostics.Process] $global:sqlcmd_process_tsqlload
[string] $global:TSQLLoadLog
[string] $global:TSQLLoadLogPath
$TSQLLoadCommonFunction = (Get-Module -Name CommonFunctions).Name
if ($TSQLLoadCommonFunction -ne "CommonFunctions")
{
#Since we are in bin and CommonFunctions is in root directory, we need to step out to import module
#This is so we can use HandleCatchBlock
$CurrentPath = Get-Location
[string]$CommonFunctionsModule = (Get-Item $CurrentPath).parent.FullName + "\CommonFunctions.psm1"
Import-Module -Name $CommonFunctionsModule
}
function Initialize-TSQLLoadLog
{
param
(
[Parameter()]
[ValidateNotNullOrEmpty()]
[string]$LogFileName = "TSQLLoadOutput.log",
[Parameter()]
[ValidateNotNullOrEmpty()]
[string]$Scenario
)
try
{
$CurrentDirectory = Get-Location
$global:TSQLLoadLogPath = (Get-Item $CurrentDirectory).parent.FullName + "\TestingInfrastructure\output\"+(Get-Date).ToString('yyyyMMddhhmmss') + '_'+ $Scenario +'_'
$global:TSQLLoadLog = $global:TSQLLoadLogPath + $LogFileName
$LogFileExistsTest = Test-Path $global:TSQLLoadLog
if ($LogFileExistsTest -eq $False)
{
New-Item -Path $global:TSQLLoadLog -ItemType File -Force| Out-Null
}
else {
Write-TSQLLoadLog "TSQLLoadLog : Starting New Capture"
}
}
catch
{
HandleCatchBlock -function_name $($MyInvocation.MyCommand) -err_rec $PSItem
}
}
function Write-TSQLLoadLog()
{
param
(
[Parameter(Position=0,Mandatory=$true)]
[Object]$Message
)
try
{
[String]$strMessage = Get-Date -Format "yyyy-MM-dd HH:mm:ss.fff"
$strMessage += " : "
$strMessage += [string]($Message)
Add-Content -Path $global:TSQLLoadLog -Value $strMessage
}
catch
{
HandleCatchBlock -function_name $($MyInvocation.MyCommand) -err_rec $PSItem
}
}
function TSQLLoadInsertsAndSelectFunction
{
param
(
[Parameter(Position=0)]
[string] $ServerName = $env:COMPUTERNAME
)
try
{
$executable = "sqlcmd.exe"
$neverending_query = "SELECT COUNT_BIG(*) FROM sys.messages a, sys.messages b, sys.messages c OPTION(MAXDOP 8)"
$query = "SET NOCOUNT ON;
DECLARE @sql_major_version INT,
@sql_major_build INT,
@sql NVARCHAR(max),
@qds_sql NVARCHAR(MAX)
SELECT @sql_major_version = (CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS varchar(20)), 4) AS INT)),
@sql_major_build = (CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS varchar(20)), 2) AS INT))
-- create some QDS actions
IF (@sql_major_version >= 13)
BEGIN
SET @qds_sql = 'IF DB_ID(''QDS_TEST_LOGSCOUT'') IS NOT NULL DROP DATABASE QDS_TEST_LOGSCOUT'
EXEC(@qds_sql)
SET @qds_sql = '
PRINT ''Creating ''''QDS_TEST_LOGSCOUT'''' database''
CREATE DATABASE QDS_TEST_LOGSCOUT'
EXEC(@qds_sql)
SET @qds_sql = 'ALTER DATABASE QDS_TEST_LOGSCOUT
SET QUERY_STORE = ON (OPERATION_MODE = READ_WRITE)'
EXEC(@qds_sql)
SET @qds_sql = 'SET NOCOUNT ON;
USE QDS_TEST_LOGSCOUT;
SELECT TOP 200 * INTO messagesA FROM sys.messages
SELECT TOP 100 * INTO messagesB FROM sys.messages
SELECT TOP 300 * INTO messagesC FROM sys.messages
SELECT TOP 5 a.message_id , b.text
FROM messagesA a
JOIN messagesB b
ON a.message_id = b.message_id
AND a.language_id = b.language_id
RIGHT JOIN messagesC c
ON b.message_id = c.message_id
AND b.language_id = c.language_id
JOIN sys.messages d
ON c.message_id = d.message_id
AND c.language_id = d.language_id '
EXEC(@qds_sql)
END
--Wait for logscout to start up for ScenarioTest
WAITFOR DELAY '00:00:30';
USE TEMPDB;
GO
IF OBJECT_ID('##TestSQLLogscoutTable') IS NOT NULL DROP TABLE ##TestSQLLogscoutTable;
GO
IF OBJECT_ID('##TestSQLLogscoutProcedure') IS NOT NULL DROP PROCEDURE ##TestSQLLogscoutProcedure;
GO
CREATE TABLE ##TestSQLLogscoutTable
([ID] int, [Description] nvarchar(128));
GO
INSERT INTO ##TestSQLLogscoutTable
VALUES (0,'Test insert from SQL_LogScout Testing Infrastructure');
GO
--This proc usually takes 30 seconds
CREATE PROCEDURE ##TestSQLLogscoutProcedure
AS
BEGIN
DECLARE @cntr int
SET @cntr = 0
WHILE @cntr<1999
BEGIN
WAITFOR DELAY '00:00:00:01'
SET @cntr = @cntr+1
INSERT INTO ##TestSQLLogscoutTable
VALUES ((select max(ID) FROM ##TestSQLLogscoutTable)+1, 'Test insert from SQL_LogScout Testing Infrastructure')
END
END
GO
--Run proc that executes 2000 times
EXEC ##TestSQLLogscoutProcedure
--Run basic select
SELECT [Description], count(*) [#Inserts]
FROM ##TestSQLLogscoutTable
GROUP BY [Description];
GO
IF OBJECT_ID('##TestSQLLogscoutTable') IS NOT NULL DROP TABLE ##TestSQLLogscoutTable;
GO
IF OBJECT_ID('##TestSQLLogscoutProcedure') IS NOT NULL DROP PROCEDURE ##TestSQLLogscoutProcedure;
GO
DECLARE @sql_major_version INT = (CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS varchar(20)), 4) AS INT)),
@qds_sql NVARCHAR(MAX)
IF (@sql_major_version >= 13)
BEGIN
SET @qds_sql = 'USE master;
IF DB_ID(''QDS_TEST_LOGSCOUT'') IS NOT NULL
BEGIN
ALTER DATABASE QDS_TEST_LOGSCOUT SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
PRINT ''Dropping ''''QDS_TEST_LOGSCOUT'''' database''
DROP DATABASE QDS_TEST_LOGSCOUT
END'
EXEC(@qds_sql)
END
"
$sqlcmd_output = $global:TSQLLoadLogPath + "TSQLLoad_SQLCmd.out"
$sqlcmd_error = $global:TSQLLoadLogPath + "TSQLLoad_SQLCmd.err"
# Start the process for never ending query execution - run it for 160 seconds and timeout
$argument_list_never_ending = "-S" + $ServerName + " -E -Hsqllogscout_loadtest -t160 -w8000 -Q`""+ $neverending_query + "`" "
Write-TSQLLoadLog "TSQLLoadLog : Never-ending argument list - $argument_list_never_ending"
$sqlcmd_process_never_ending = Start-Process -FilePath $executable -ArgumentList $argument_list_never_ending -WindowStyle Hidden -PassThru -RedirectStandardError $sqlcmd_error
Write-TSQLLoadLog "TSQLLoadLog : Started Load Script"
Write-TSQLLoadLog "TSQLLoadLog : Process ID for Never-ending Test Load is: $sqlcmd_process_never_ending"
# Start the process for the bigger workload
$argument_list = "-S" + $ServerName + " -E -Hsqllogscout_loadtest -w8000 -Q`""+ $query + "`" "
Write-TSQLLoadLog "TSQLLoadLog : Argument List - $argument_list"
$sqlcmd_process_tsqlload = Start-Process -FilePath $executable -ArgumentList $argument_list -WindowStyle Hidden -PassThru -RedirectStandardOutput $sqlcmd_output
$global:sqlcmd_process_tsqlload = $sqlcmd_process_tsqlload.Id
Write-TSQLLoadLog "TSQLLoadLog : Process ID for Test Load is: $global:sqlcmd_process_tsqlload"
}
catch
{
HandleCatchBlock -function_name $($MyInvocation.MyCommand) -err_rec $PSItem
}
}
function TSQLLoadCheckWorkloadExited ()
{
try
{
while ($false -eq $global:sqlcmd_process_tsqlload.HasExited)
##Logically we should never enter this code as this tsql load should have completed before logscout finished. If we are hung for some reason, we need to terminate the process.
{
Stop-Process $global:sqlcmd_process_tsqlload
Write-TSQLLoadLog "TSQLLoadLog : TSQL Load Terminated Due to Long Duration"
}
Write-TSQLLoadLog "TSQLLoadLog : Process exited as expected"
}
catch
{
HandleCatchBlock -function_name $($MyInvocation.MyCommand) -err_rec $PSItem
}
}

Просмотреть файл

@ -30,11 +30,20 @@ param(
[string]$SummaryFilename = ".\output\SUMMARY.TXT",
[Parameter()]
[string]$DetailedFilename = ".\output\DETAILED.TXT"
[string]$DetailedFilename = ".\output\SearchForErrors_Detailed.TXT"
)
try {
$return_val = $true
#clear contents of the detailed file
if (Test-Path $DetailedFilename)
{
Clear-Content -Path $DetailedFilename
}
#search the debug log for errors
$AllMatches = Select-String -Path $LogNamePattern -Pattern $MessagePatterns
[System.Text.StringBuilder]$detailedOutput = New-Object -TypeName System.Text.StringBuilder
@ -56,6 +65,12 @@ param(
[void]$detailedOutput.AppendLine($Match.LineNumber.ToString() + ": " + $Match.Line)
}
#write to the detailed output to file if there is any error found
if (-not([string]::IsNullOrWhiteSpace($detailedOutput.ToString()))){
$detailedOutput.ToString() | Out-File $DetailedFilename -Append
}
#write summary to file
$SummaryMsg = "Total Error Pattern Match: " + $AllMatches.Matches.Count.ToString()
if(0 -eq $AllMatches.Matches.Count)
@ -64,15 +79,25 @@ param(
}
else
{
$SummaryMsg = ($SummaryMsg + " "*(60 - $SummaryMsg.Length) + "ERRORS FOUND!")
# build the full path to the detailed file
$cwd = (Get-location).Path
$detailedFileFullPath = (Join-Path $cwd $DetailedFilename) | Resolve-Path
$SummaryMsg = ($SummaryMsg + " "*(60 - $SummaryMsg.Length) + "ERRORS FOUND! (See '$detailedFileFullPath' for more details)")
$return_val = $false
}
Write-Output ($SummaryMsg) | Out-File $SummaryFilename -Append
if (-not([string]::IsNullOrWhiteSpace($detailedOutput.ToString()))){
$detailedOutput.ToString() | Out-File $DetailedFilename -Append
}
if ($return_val -eq $false)
{
Write-Host "Printing detailed Search-Log test output '$detailedFileFullPath)':`n"
Get-Content -Path $DetailedFilename | Out-Host
}
return $return_val
}
catch {
@ -81,6 +106,6 @@ param(
$error_offset = $PSItem.InvocationInfo.OffsetInLine
$error_script = $PSItem.InvocationInfo.ScriptName
Write-LogError "Function '$($MyInvocation.MyCommand)' failed with error: $error_msg (line: $error_linenum, offset: $error_offset, file: $error_script)"
$return_val = $false
}
}

Просмотреть файл

@ -0,0 +1,13 @@
@echo off
echo.
echo *****************************************************************
echo Starting Tests Infrastructure
echo *****************************************************************
echo.
powershell.exe -ExecutionPolicy Bypass -File FilecountandtypeValidation.ps1 2> .\##TestFailures.LOG
powershell.exe -ExecutionPolicy Bypass -File ..\StdErrorOutputHandling.ps1 .\##TestFailures.LOG

Просмотреть файл

@ -39,6 +39,21 @@ function GetExclusionsInclusions ([string]$Scenario)
$RetExclusion = "ReplMetaData"
}
}
"AlwaysOn"
{
if ($true -eq (CheckLogsForString -TextToFind "HADR is off, skipping data movement and AG Topology" ))
{
$RetExclusion = "NoAlwaysOn"
}
}
"NeverEndingQuery"
{
if ($true -eq (CheckLogsForString -TextToFind "NeverEndingQuery Exit without collection"))
{
$RetExclusion = "NoNeverEndingQuery"
}
}
}
return $RetExclusion
@ -65,7 +80,7 @@ function CheckLogsForString()
#We didn't find the provided text
else
{
Write-Output "No ##SQLLogScout logs contains the stirng provided" | Out-File $global:ReportFileSQLNexus -Append
Write-Output "No ##SQLLogScout logs contains the string provided" | Out-File $global:ReportFileSQLNexus -Append
}
return $false
@ -74,16 +89,27 @@ function CheckLogsForString()
try
{
$return_val = $true
$testingFolder = $SQLLogScoutRootFolder + "\Bin\TestingInfrastructure\"
$global:ReportFileSQLNexus = $testingFolder + "output\" + (Get-Date).ToString('yyyyMMddhhmmss') + '_'+ $Scenarios +'_SQLNexusOutput.txt'
$out_string = "SQLNexus '$Scenarios' scenario test:"
$global:SQLLogScoutLog = $LogScoutOutputFolder + "\internal\##SQLLOGSCOUT.LOG"
$global:SQLLogScoutDebugLog = $LogScoutOutputFolder + "\internal\##SQLLOGSCOUT_DEBUG.LOG"
#if SQLNexus.exe path is provided we run the test
if ($SqlNexusPath -ne "")
{
Write-LogInformation "Importing the log in SQL database using SQLNexus.exe"
#check if multiple scenarios are provided and exit if so
if ($Scenarios.Split("+").Count -gt 1)
{
$out_string = ($out_string + " "*(60 - $out_string.Length) + "FAILED!!! SQLNexus_Test does not support multiple scenarios (only single scenario).")
Write-Output $out_string | Out-File $OutputFilename -Append
return $false
}
$sqlnexus_imp_msg = "Importing logs in SQL database '$SqlNexusDb' using SQLNexus.exe"
Write-Host $sqlnexus_imp_msg
Write-Host "SQL LogScout assumes you have already downloaded SQLNexus.exe. If not, please download it here -> https://github.com/Microsoft/SqlNexus/releases "
@ -91,7 +117,9 @@ try
if (Test-Path -Path ($executable))
{
Write-Host "SQLNexus.exe found. Executing test..."
$sqlnexus_version = (Get-Item $executable).VersionInfo.ProductVersion
$sqlnexus_found = "SQLNexus.exe v$sqlnexus_version found. Executing test..."
Write-Host $sqlnexus_found
#launch SQLNexus and wait for it to finish processing -Wait before continuing
@ -114,7 +142,7 @@ try
#execute the stored procedure
$sqlnexus_query = "exec tempdb.dbo.proc_SqlNexusTableValidation '" + $Scenarios + "', '" + $SqlNexusDb + "', '" + $ExclusionTag + "'"
$argument_list2 = "-S" + '"'+ $ServerName +'"' + " -d" + '"'+ $SqlNexusDb +'"' + " -E -Hsqllogscout_sqlnexustest -w8000" + " -Q" + '"EXIT('+ $sqlnexus_query +')"' + " -o" + '"'+ $global:ReportFileSQLNexus +'"'
$proc = Start-Process -FilePath $executable -ArgumentList $argument_list2 -WindowStyle Hidden -Wait -PassThru
$proc = Start-Process -FilePath $executable -ArgumentList $argument_list2 -WindowStyle Hidden -Wait -PassThru
if ($proc)
{
@ -123,15 +151,18 @@ try
if($proc.ExitCode -eq 2002002)
{
#there are tables that are not present. report in summary file
$out_string = ($out_string + " "*(60 - $out_string.Length) + "FAILED!!! Found missing tables; see '$global:ReportFileSQLNexus'")
$out_string = ($out_string + " "*(60 - $out_string.Length) + "FAILED!!! (Found missing tables; see '$global:ReportFileSQLNexus')")
$return_val = $false
}
elseif ($proc.ExitCode -eq 1001001)
{
$out_string = ($out_string + " "*(60 - $out_string.Length) + "SUCCESS ")
}
else
{
$out_string = ($out_string + " "*(60 - $out_string.Length) + "FAILED!!! Query/script failure of some kind. Exit code = '$($proc.ExitCode)' ")
$return_val = $false
}
Write-Output $out_string | Out-File $OutputFilename -Append
@ -156,8 +187,25 @@ try
# write out to the summary file
$out_string = ($out_string + " "*(60 - $out_string.Length) + "FAILED!!! SQLNexus.exe not found. See '$global:ReportFileSQLNexus'")
Write-Output $out_string | Out-File $OutputFilename -Append
$return_val = $false
}
#append several message to the datetime_scenario_SQLNexusOutput.txt file
$storedproc_results = Get-Content -Path $global:ReportFileSQLNexus
Set-Content -Path $global:ReportFileSQLNexus -Value $sqlnexus_imp_msg
Add-Content -Path $global:ReportFileSQLNexus -Value $sqlnexus_found
Add-Content -Path $global:ReportFileSQLNexus -Value ""
Add-Content -Path $global:ReportFileSQLNexus -Value $storedproc_results
}
# if some error occurred, print the report file to the console (for debugging purposes)
if ($return_val -eq $false)
{ Write-Host "Printing detailed SQLNexus test output '$global:ReportFileSQLNexus':`n"
Get-Content -Path $global:ReportFileSQLNexus | Out-Host
}
return $return_val
}
catch
{
@ -167,5 +215,5 @@ catch
$error_linenum = $PSItem.InvocationInfo.ScriptLineNumber
$error_offset = $PSItem.InvocationInfo.OffsetInLine
Write-LogError "Function $mycommand failed with error: $error_msg (line: $error_linenum, $error_offset)"
return
return $false
}

Просмотреть файл

@ -23,7 +23,10 @@ param
[string] $RootFolder,
[Parameter(Position=7)]
[bool] $RunTSQLLoad = $false
[bool] $RunTSQLLoad = $false,
[Parameter(Position=8)]
[string] $DisableCtrlCasInput = "False"
)
$TSQLLoadModule = (Get-Module -Name TSQLLoadModule).Name
@ -61,19 +64,33 @@ Write-Output " $(Get-Date -Format "dd MMMM yyyy HH:mm:ss")
Write-Output " Server Name: $ServerName "
Write-Output "********************************************************************"
[bool] $script_ret = $true
[int] $return_val = 0
# validate root folder
$PathFound = Test-Path -Path $RootFolder
if ($PathFound -eq $false)
{
Write-Host "Invalid Root directory for testing. Exiting."
exit
$return_val = 4
return $return_val
}
# start and stop times for LogScout execution
$StartTime = (Get-Date).AddSeconds(20)
$StopTime = (Get-Date).AddMinutes(2)
if ($Scenarios -match "NeverEndingQuery"){
# NeverEndingQuery scenario needs 60 seconds to run before test starts so we can accumulate 60 seconds of CPU time
$StartTime = (Get-Date).AddSeconds(60).ToString("yyyy-MM-dd HH:mm:ss")
}
else {
$StartTime = (Get-Date).AddSeconds(20).ToString("yyyy-MM-dd HH:mm:ss")
}
# stop time is 3 minutes from start time. This is to ensure that we have enough data to analyze
# also ensures that on some machines where the test runs longer, we don't lose logs due to the test ending prematurely
$StopTime = (Get-Date).AddMinutes(3).ToString("yyyy-MM-dd HH:mm:ss")
# start TSQLLoad execution
if ($RunTSQLLoad -eq $true)
{
Initialize-TSQLLoadLog -Scenario $Scenarios
@ -81,34 +98,64 @@ if ($RunTSQLLoad -eq $true)
TSQLLoadInsertsAndSelectFunction -ServerName $ServerName
}
##execute a regular SQL LogScout data collection from root folder
Write-Host "Starting LogScout"
&($RootFolder + "\SQL_LogScout.cmd") $Scenarios $ServerName "UsePresentDir" "DeleteDefaultFolder" $StartTime $StopTime "Quiet"
#build command line and arguments
$LogScoutCmd = "`"" + $RootFolder + "\SQL_LogScout.cmd" + "`""
$argument_list = $Scenarios + " `"" + $ServerName + "`" UsePresentDir DeleteDefaultFolder `"" + $StartTime.ToString() + "`" `"" + $StopTime.ToString() + "`" Quiet " + $DisableCtrlCasInput
#execute LogScout
Start-Process -FilePath $LogScoutCmd -ArgumentList $argument_list -Wait -NoNewWindow
Write-Host "LogScoutCmd: $LogScoutCmd"
Write-Host "Argument_list: $argument_list"
if ($RunTSQLLoad -eq $true)
{
Write-Host "Verifying workload finished"
Write-Host "Verifying T-SQL workload finished"
TSQLLoadCheckWorkloadExited
}
#run file validation test
./FilecountandtypeValidation.ps1 -SummaryOutputFile $SummaryOutputFile 2> .\##TestFailures.LOG
$script_ret = ./FilecountandtypeValidation.ps1 -SummaryOutputFile $SummaryOutputFile 2> .\##TestFailures.LOG
..\StdErrorOutputHandling.ps1 -FileName .\##TestFailures.LOG
if ($script_ret -eq $false)
{
#FilecountandtypeValidation test failed, return a unique, non-zero value
$return_val = 1
}
#check SQL_LOGSCOUT_DEBUG log for errors
. .\LogParsing.ps1
# $LogNamePattern defaults to "..\output\internal\##SQLLOGSCOUT_DEBUG.LOG"
# $SummaryFilename defaults to ".\output\SUMMARY.TXT"
# $DetailedFilename defaults to ".\output\DETAILED.TXT"
Search-Log -LogNamePattern ($RootFolder + "\output\internal\##SQLLOGSCOUT_DEBUG.LOG")
$script_ret = Search-Log -LogNamePattern ($RootFolder + "\output\internal\##SQLLOGSCOUT_DEBUG.LOG")
if ($script_ret -eq $false)
{
#Search-Log test failed, return a unique, non-zero value
$return_val = 2
}
#run SQLNexus import and table verficiation test
.\SQLNexus_Test.ps1 -ServerName $ServerName -Scenarios $Scenarios -OutputFilename $SummaryOutputFile -SqlNexusPath $SqlNexusPath -SqlNexusDb $SqlNexusDb -LogScoutOutputFolder $LogScoutOutputFolder -SQLLogScoutRootFolder $RootFolder
$script_ret = .\SQLNexus_Test.ps1 -ServerName $ServerName -Scenarios $Scenarios -OutputFilename $SummaryOutputFile -SqlNexusPath $SqlNexusPath -SqlNexusDb $SqlNexusDb -LogScoutOutputFolder $LogScoutOutputFolder -SQLLogScoutRootFolder $RootFolder
if ($script_ret -eq $false)
{
#SQLNexus test failed, return a non-zero value
$return_val = 3
}
Write-Host "Scenario_Test return value: $return_val" | Out-Null
return $return_val

Просмотреть файл

@ -0,0 +1,248 @@
# # Starter pipeline
# Start with a minimal pipeline that you can customize to build and deploy your code.
# Add steps that build, run tests, deploy, and more:
# https://aka.ms/yaml
trigger:
- master
pool:
vmImage: windows-latest
steps:
- script: echo Start Pipeline!
displayName: 'Run a one-line script'
- task: PSScriptAnalyzer@1
inputs:
Path: '$(Build.SourcesDirectory)'
Settings: 'required'
Recurse: true
- task: AntiMalware@4
inputs:
InputType: 'Basic'
ScanType: 'CustomScan'
FileDirPath: '$(Build.StagingDirectory)'
TreatSignatureUpdateFailureAs: 'Warning'
SignatureFreshness: 'UpToDate'
TreatStaleSignatureAs: 'Error'
- task: ComponentGovernanceComponentDetection@0
inputs:
scanType: 'Register'
verbosity: 'Verbose'
alertWarningLevel: 'High'
- task: CredScan@3
- task: Guardian@1
inputs:
break: true
- task: PostAnalysis@2
inputs:
GdnBreakAllTools: true
- task: ManifestGeneratorTask@0
inputs:
BuildDropPath: '$(Build.ArtifactStagingDirectory)'
# for now disabling publish artifacts task
#- task: PublishPipelineArtifact@1
# inputs:
# targetPath: '$(Pipeline.Workspace)/a/_manifest/spdx_2.2'
# artifact: 'PipelineArtifacts'
# publishLocation: 'pipeline'
- task: PowerShell@2
displayName: Version check - Powershell and .NET Framework
inputs:
targetType: 'inline'
script: |
Write-Host "PowerShell version:"
$PSVersionTable.PSVersion
Write-Host "-----------------------------"
$release = Get-ItemPropertyValue -LiteralPath 'HKLM:SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full' -Name Release
switch ($release) {
{ $_ -ge 533320 } { $version = '4.8.1 or later'; break }
{ $_ -ge 528040 } { $version = '4.8'; break }
{ $_ -ge 461808 } { $version = '4.7.2'; break }
{ $_ -ge 461308 } { $version = '4.7.1'; break }
{ $_ -ge 460798 } { $version = '4.7'; break }
{ $_ -ge 394802 } { $version = '4.6.2'; break }
{ $_ -ge 394254 } { $version = '4.6.1'; break }
{ $_ -ge 393295 } { $version = '4.6'; break }
{ $_ -ge 379893 } { $version = '4.5.2'; break }
{ $_ -ge 378675 } { $version = '4.5.1'; break }
{ $_ -ge 378389 } { $version = '4.5'; break }
default { $version = $null; break }
}
if ($version) {
Write-Host -Object ".NET Framework Version: $version"
} else {
Write-Host -Object '.NET Framework Version 4.5 or later is not detected.'
}
- task: CmdLine@2
displayName: Install Nexus Prerequisites
inputs:
script: |
echo Downloading Nexus prerequisites...
curl.exe --output .\sqlnexus_install_components\SQLSysClrTypes.msi --create-dirs --url https://download.microsoft.com/download/B/1/7/B1783FE9-717B-4F78-A39A-A2E27E3D679D/ENU/x64/SQLSysClrTypes.msi
curl.exe --output .\sqlnexus_install_components\ReportViewer.msi --url https://download.microsoft.com/download/B/1/7/B1783FE9-717B-4F78-A39A-A2E27E3D679D/ENU/x86/ReportViewer.msi
curl.exe --output .\sqlnexus_install_components\RMLSetup.msi --url https://download.microsoft.com/download/a/a/d/aad67239-30df-403b-a7f1-976a4ac46403/RMLSetup.msi
echo:
cd sqlnexus_install_components
dir
echo:
echo Installing CLR types...
SQLSysClrTypes.msi -passive
echo Installing RML Utilities...
RMLSetup.msi -passive
echo Installing Report Viewer Control...
ReportViewer.msi -passive
echo:
echo Testing ReadTrace...
"C:\Program Files\Microsoft Corporation\RMLUtils\ReadTrace.exe" /? & echo:
if %ERRORLEVEL% equ 9009 echo Could not find ReadTrace.exe, listing directory for user verification: & echo: & dir "C:\Program Files\Microsoft Corporation\RMLUtils" & exit 100001
if %ERRORLEVEL% equ -6 echo RML Utilities installed successfully!
echo:
echo Checking SQL CLR Types...
if exist C:\Windows\System32\SqlServerSpatial130.dll echo SQL CLR Types installed successfully!
if NOT exist C:\Windows\System32\SqlServerSpatial130.dll echo SQL CLR Types not found! & exit 100002
echo:
echo Checking ReportViewer...
if exist C:\Windows\Microsoft.NET\assembly\GAC_MSIL\Microsoft.ReportViewer.Common.resources\v4.0_13.0.0.0_es_89845dcd8080cc91\Microsoft.ReportViewer.Common.resources.dll echo Resource Viewer installed successfully!
if NOT exist C:\Windows\Microsoft.NET\assembly\GAC_MSIL\Microsoft.ReportViewer.Common.resources\v4.0_13.0.0.0_es_89845dcd8080cc91\Microsoft.ReportViewer.Common.resources.dll echo Resource Viewer not found! & exit 100003
echo:
cd ..
echo Downloading SQL Nexus latest binaries...
curl.exe -L --output .\sqlnexus\SQLNexus_Signed.zip --create-dirs --url https://aka.ms/get-sqlnexus
- task: ExtractFiles@1
displayName: Extract Nexus Zip
inputs:
archiveFilePatterns: '.\sqlnexus\SQLNexus_Signed.zip'
destinationFolder: '.\sqlnexus'
cleanDestinationFolder: false
overwriteExistingFiles: false
- task: CmdLine@2
displayName: Install Nexus
inputs:
script: |
echo Listing Nexus directory...
cd sqlnexus
dir
echo ##vso[task.setvariable variable=CWD;]%CD%
echo Testing Nexus...
sqlnexus.exe /? & echo:
if %ERRORLEVEL% neq -1 echo Failed to call sqlnexus.exe & exit 100004
if %ERRORLEVEL% equ -1 echo SQL Nexus has installed successfully! & (call )
- task: CmdLine@2
displayName: Install SQL Server and test a connection
inputs:
script: |
time /t
echo ========================================================================================
echo Downloading SQL Express...
curl.exe https://download.microsoft.com/download/5/1/4/5145fe04-4d30-4b85-b0d1-39533663a2f1/SQL2022-SSEI-Expr.exe --output .\SQL2022-SSEI-Expr.exe --silent
echo List current folder content
dir
echo ========================================================================================
echo Installing SQL Express. Wait for install to finish...
start /wait .\SQL2022-SSEI-Expr.exe /Action=Install /Language=en-US /ENU /HideProgressBar /IAcceptSqlServerLicenseTerms /InstallPath="c:\Program Files\Microsoft SQL Server" /Quiet
echo SQL Express installation finished!
setx /M PATH "%PATH%;c:\Program Files\Microsoft SQL Server\Client SDK\ODBC\170\Tools\Binn\"
echo ========================================================================================
echo Connect to SQL Server and run a test query
sqlcmd -S.\sqlexpress -Q "set nocount on; SELECT @@version; SELECT @@servername"
date /t & time /t
- task: CmdLine@2
displayName: Run LogScout Test Suite
inputs:
script: |
time /t
sqlcmd -S.\sqlexpress -Q "set nocount on; SELECT @@version; SELECT @@servername; SELECT * FROM sys.databases"
echo ========================================================================================
echo Starting SQL LogScout test...
date /t & time /t
cd .\Bin\TestingInfrastructure
powershell -File .\ConsistentQualityTests.ps1 -ServerName ".\sqlexpress" -Scenarios "Basic" -SqlNexusPath $(CWD) -SqlNexusDb "SqlNexusDB" -DisableCtrlCasInput "True"
IF %ERRORLEVEL% GTR 0 echo ##[error]Test failed with errorlevel %ERRORLEVEL% && exit 1
powershell -File .\ConsistentQualityTests.ps1 -ServerName ".\sqlexpress" -Scenarios "GeneralPerf+NoBasic" -SqlNexusPath $(CWD) -SqlNexusDb "SqlNexusDB" -DisableCtrlCasInput "True"
IF %ERRORLEVEL% GTR 0 echo ##[error]Test failed with errorlevel %ERRORLEVEL% && exit 1
powershell -File .\ConsistentQualityTests.ps1 -ServerName ".\sqlexpress" -Scenarios "DetailedPerf+NoBasic" -SqlNexusPath $(CWD) -SqlNexusDb "SqlNexusDB" -DisableCtrlCasInput "True"
IF %ERRORLEVEL% GTR 0 echo ##[error]Test failed with errorlevel %ERRORLEVEL% && exit 1
powershell -File .\ConsistentQualityTests.ps1 -ServerName ".\sqlexpress" -Scenarios "LightPerf+NoBasic" -SqlNexusPath $(CWD) -SqlNexusDb "SqlNexusDB" -DisableCtrlCasInput "True"
IF %ERRORLEVEL% GTR 0 echo ##[error]Test failed with errorlevel %ERRORLEVEL% && exit 1
powershell -File .\ConsistentQualityTests.ps1 -ServerName ".\sqlexpress" -Scenarios "Memory+NoBasic" -SqlNexusPath $(CWD) -SqlNexusDb "SqlNexusDB" -DisableCtrlCasInput "True"
IF %ERRORLEVEL% GTR 0 echo ##[error]Test failed with errorlevel %ERRORLEVEL% && exit 1
powershell -File .\ConsistentQualityTests.ps1 -ServerName ".\sqlexpress" -Scenarios "AlwaysOn+NoBasic" -SqlNexusPath $(CWD) -SqlNexusDb "SqlNexusDB" -DisableCtrlCasInput "True"
IF %ERRORLEVEL% GTR 0 echo ##[error]Test failed with errorlevel %ERRORLEVEL% && exit 1
powershell -File .\ConsistentQualityTests.ps1 -ServerName ".\sqlexpress" -Scenarios "NetworkTrace+NoBasic" -SqlNexusPath $(CWD) -SqlNexusDb "SqlNexusDB" -DisableCtrlCasInput "True"
IF %ERRORLEVEL% GTR 0 echo ##[error]Test failed with errorlevel %ERRORLEVEL% && exit 1
powershell -File .\ConsistentQualityTests.ps1 -ServerName ".\sqlexpress" -Scenarios "IO+NoBasic" -SqlNexusPath $(CWD) -SqlNexusDb "SqlNexusDB" -DisableCtrlCasInput "True"
IF %ERRORLEVEL% GTR 0 echo ##[error]Test failed with errorlevel %ERRORLEVEL% && exit 1
powershell -File .\ConsistentQualityTests.ps1 -ServerName ".\sqlexpress" -Scenarios "BackupRestore+NoBasic" -SqlNexusPath $(CWD) -SqlNexusDb "SqlNexusDB" -DisableCtrlCasInput "True"
IF %ERRORLEVEL% GTR 0 echo ##[error]Test failed with errorlevel %ERRORLEVEL% && exit 1
powershell -File .\ConsistentQualityTests.ps1 -ServerName ".\sqlexpress" -Scenarios "Replication+NoBasic" -SqlNexusPath $(CWD) -SqlNexusDb "SqlNexusDB" -DisableCtrlCasInput "True"
IF %ERRORLEVEL% GTR 0 echo ##[error]Test failed with errorlevel %ERRORLEVEL% && exit 1
powershell -File .\ConsistentQualityTests.ps1 -ServerName ".\sqlexpress" -Scenarios "Setup+NoBasic" -SqlNexusPath $(CWD) -SqlNexusDb "SqlNexusDB" -DisableCtrlCasInput "True"
IF %ERRORLEVEL% GTR 0 echo ##[error]Test failed with errorlevel %ERRORLEVEL% && exit 1
powershell -File .\ConsistentQualityTests.ps1 -ServerName ".\sqlexpress" -Scenarios "ServiceBrokerDBMail+NoBasic" -DisableCtrlCasInput "True"
IF %ERRORLEVEL% GTR 0 echo ##[error]Test failed with errorlevel %ERRORLEVEL% && exit 1
powershell -File .\ConsistentQualityTests.ps1 -ServerName ".\sqlexpress" -Scenarios "GeneralPerf+Replication" -SqlNexusPath $(CWD) -SqlNexusDb "SqlNexusDB" -DisableCtrlCasInput "True"
IF %ERRORLEVEL% GTR 0 echo ##[error]Test failed with errorlevel %ERRORLEVEL% && exit 1
powershell -File .\ConsistentQualityTests.ps1 -ServerName ".\sqlexpress" -Scenarios "GeneralPerf+AlwaysOn" -SqlNexusPath $(CWD) -SqlNexusDb "SqlNexusDB" -DisableCtrlCasInput "True"
IF %ERRORLEVEL% GTR 0 echo ##[error]Test failed with errorlevel %ERRORLEVEL% && exit 1
powershell -File .\ConsistentQualityTests.ps1 -ServerName ".\sqlexpress" -Scenarios "GeneralPerf+IO"- -SqlNexusPath $(CWD) -SqlNexusDb "SqlNexusDB" -DisableCtrlCasInput "True"
IF %ERRORLEVEL% GTR 0 echo ##[error]Test failed with errorlevel %ERRORLEVEL% && exit 1
powershell -File .\ConsistentQualityTests.ps1 -ServerName ".\sqlexpress" -Scenarios "GeneralPerf+NetworkTrace" -SqlNexusPath $(CWD) -SqlNexusDb "SqlNexusDB" -DisableCtrlCasInput "True"
IF %ERRORLEVEL% GTR 0 echo ##[error]Test failed with errorlevel %ERRORLEVEL% && exit 1
powershell -File .\ConsistentQualityTests.ps1 -ServerName ".\sqlexpress" -Scenarios "GeneralPerf+Memory" -SqlNexusPath $(CWD) -SqlNexusDb "SqlNexusDB" -DisableCtrlCasInput "True"
IF %ERRORLEVEL% GTR 0 echo ##[error]Test failed with errorlevel %ERRORLEVEL% && exit 1
powershell -File .\ConsistentQualityTests.ps1 -ServerName ".\sqlexpress" -Scenarios "GeneralPerf+ServiceBrokerDBMail" -DisableCtrlCasInput "True"
IF %ERRORLEVEL% GTR 0 echo ##[error]Test failed with errorlevel %ERRORLEVEL% && exit 1
date /t & time /t

Просмотреть файл

@ -50,6 +50,12 @@ BEGIN
@sql_major_build = MajorBuild
FROM #sqlversion
DECLARE @SQLVERSION BIGINT = PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS VARCHAR(20)), 4)
+ RIGHT(REPLICATE ('0', 3) + PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS VARCHAR(20)), 3), 3)
+ RIGHT (replicate ('0', 6) + PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS VARCHAR(20)), 2) , 6)
--Implement the exceptions now. #temptablelist_sqlnexus is already created by parent proc so it exist in this session
-- exclude scoped configuration table in versions earlier than SQL 2016
@ -103,6 +109,17 @@ BEGIN
)
END
-- in-memory related dmvs
IF (@sql_major_version < 12)
BEGIN
DELETE FROM #temptablelist_sqlnexus
WHERE SchemaName = 'dbo'
AND TableName IN (
'tbl_dm_db_xtp_transactions',
'tbl_dm_xtp_transaction_stats'
)
END
END
@ -149,6 +166,11 @@ BEGIN
'tbl_hadr_ag_automatic_seeding',
'tbl_hadr_ag_physical_seeding_stats')
END
IF (@exclusion_tag = 'NoAlwaysOn')
BEGIN
DELETE FROM #temptablelist_sqlnexus
WHERE SchemaName = 'ReadTrace'
END
END
@ -202,6 +224,37 @@ BEGIN
END
END
--exclude in-memory dvms from before SQL 2014
ELSE IF (@scenario_name IN ('Memory'))
BEGIN
IF (@sql_major_version < 12)
BEGIN
DELETE FROM #temptablelist_sqlnexus
WHERE SchemaName = 'dbo'
AND TableName IN (
'tbl_dm_db_xtp_index_stats'
,'tbl_dm_db_xtp_hash_index_stats'
,'tbl_dm_db_xtp_table_memory_stats'
,'tbl_dm_db_xtp_memory_consumers'
,'tbl_dm_db_xtp_object_stats'
,'tbl_dm_xtp_system_memory_consumers'
,'tbl_dm_xtp_system_memory_consumers_summary'
,'tbl_dm_xtp_gc_stats'
,'tbl_dm_xtp_gc_queue_stats')
END
END
-- Exclued Neverneding Query tables
ELSE IF (@scenario_name IN ('NeverEndingQuery'))
BEGIN
IF (@SQLVERSION < 13000004001 OR @exclusion_tag = 'NoNeverEndingQuery')
BEGIN
DELETE FROM #temptablelist_sqlnexus
END
END
END
GO
@ -213,7 +266,22 @@ AS
BEGIN
SET NOCOUNT ON
-- Validate the parameter db name and scenario name
IF (EXISTS (SELECT name FROM master.sys.databases WHERE (name = @databasename)) and @scenarioname in ('AlwaysOn','GeneralPerf','DetailedPerf','Setup','Basic','BackupRestore','IO','LightPerf','Replication'))
-- only accept single scenario names (no combinations)
IF (EXISTS (SELECT name FROM master.sys.databases WHERE (name = @databasename))
and @scenarioname in (
'AlwaysOn',
'GeneralPerf',
'DetailedPerf',
'Memory',
'Setup',
'Basic',
'BackupRestore',
'IO',
'LightPerf',
'Replication',
'ServiceBrokerDBMail',
'NeverEndingQuery')
)
BEGIN
IF OBJECT_ID('tempdb..#temptablelist_sqlnexus') IS NOT NULL
BEGIN
@ -264,7 +332,9 @@ BEGIN
('dbo','tbl_dm_db_log_info'),
('dbo','Counters'),
('dbo','CounterDetails'),
('dbo','CounterData')
('dbo','CounterData'),
('dbo', 'tbl_SystemInformation'),
('dbo', 'tbl_environment_variables')
--create the list of Basic scenario tables for reuse in other scenarios
IF OBJECT_ID('tempdb..#tablelist_LightPerfScenario') IS NOT NULL
@ -339,7 +409,9 @@ BEGIN
('dbo','tbl_query_store_query_variant'),
('dbo','tbl_profiler_trace_summary') ,
('dbo','tbl_profiler_trace_event_details') ,
('dbo','tbl_XEvents')
('dbo','tbl_XEvents'),
('dbo','tbl_dm_db_xtp_transactions'),
('dbo','tbl_dm_xtp_transaction_stats')
--now go through each scenario and the tables expected for it
IF (@scenarioname = 'AlwaysOn')
@ -387,7 +459,7 @@ BEGIN
('ReadTrace','tblUniqueLoginNames'),
('dbo','CounterDetails'),
('dbo','CounterData'),
('dbo','DisplayToID')
('dbo','DisplayToID')
--insert the tables for Basic scenario
INSERT INTO #temptablelist_sqlnexus (SchemaName,TableName)
@ -536,12 +608,70 @@ BEGIN
('dbo','tbl_repl_mstracer_tokens'),
('dbo','tbl_repl_sysservers'),
('dbo','tbl_Reports')
--insert the tables for Basic scenario
INSERT INTO #temptablelist_sqlnexus (SchemaName,TableName)
SELECT SchemaName,TableName FROM #tablelist_BasicScenario
END
ELSE IF (@scenarioname = 'Memory')
BEGIN
INSERT INTO #temptablelist_sqlnexus (SchemaName,TableName) VALUES
('dbo','tbl_Query_Execution_Memory_MemScript'),
('dbo','tbl_proccache_summary'),
('dbo','tbl_proccache_pollution'),
('dbo','tbl_DM_OS_MEMORY_CACHE_COUNTERS'),
('dbo','tbl_DM_OS_MEMORY_CLERKS'),
('dbo','tbl_DM_OS_MEMORY_CACHE_CLOCK_HANDS'),
('dbo','tbl_DM_OS_MEMORY_CACHE_HASH_TABLES'),
('dbo','tbl_dm_os_memory_pools'),
('dbo','tbl_dm_os_loaded_modules_non_microsoft'),
('dbo','tbl_dm_os_memory_objects'),
('dbo','tbl_workingset_trimming'),
('dbo','tbl_dm_os_ring_buffers_mem'),
('dbo','tbl_dm_db_xtp_index_stats'),
('dbo','tbl_dm_db_xtp_hash_index_stats'),
('dbo','tbl_dm_db_xtp_table_memory_stats'),
('dbo','tbl_dm_db_xtp_memory_consumers'),
('dbo','tbl_dm_db_xtp_object_stats'),
('dbo','tbl_dm_xtp_system_memory_consumers'),
('dbo','tbl_dm_xtp_system_memory_consumers_summary'),
('dbo','tbl_dm_xtp_gc_stats'),
('dbo','tbl_dm_xtp_gc_queue_stats')
--add the basic scenario tables
INSERT INTO #temptablelist_sqlnexus (SchemaName,TableName)
SELECT SchemaName,TableName FROM #tablelist_BasicScenario
END
ELSE IF (@scenarioname = 'ServiceBrokerDBMail')
BEGIN
INSERT INTO #temptablelist_sqlnexus (SchemaName,TableName) VALUES
('dbo','tbl_sysmail_profileaccount'),
('dbo','tbl_sysmail_profile'),
('dbo','tbl_sysmail_log'),
('dbo','tbl_sysmail_configuration'),
('dbo','tbl_sysmail_account'),
('dbo','tbl_sysmail_mailitems'),
('dbo','tbl_sysmail_event_log_sysmail_faileditems')
--add the basic scenario tables
INSERT INTO #temptablelist_sqlnexus (SchemaName,TableName)
SELECT SchemaName,TableName FROM #tablelist_BasicScenario
END
ELSE IF (@scenarioname = 'NeverEndingQuery')
BEGIN
INSERT INTO #temptablelist_sqlnexus (SchemaName,TableName) VALUES
('dbo','tbl_CPU_bound_query_never_completes')
--add the basic scenario tables
INSERT INTO #temptablelist_sqlnexus (SchemaName,TableName)
SELECT SchemaName,TableName FROM #tablelist_BasicScenario
END
--call the stored proc to implement exceptions
EXEC dbo.proc_ExclusionsInclusions @scenario_name = @scenarioname , @database_name = @databasename, @exclusion_tag = @exclusion
@ -568,6 +698,12 @@ BEGIN
SELECT 1001001 AS EXIT_CODE
END
END
ELSE
BEGIN
--if the db name or scenario name is invalid, send some large value code out to indicate failure
SELECT 'Scenario name or database name is invalid' as 'Error_Message'
SELECT 3003003 AS EXIT_CODE
END
END
GO
--exec tempdb..proc_SqlNexusTableValidation 'LightPerf','sqlnexus'

Просмотреть файл

@ -1,17 +0,0 @@
set nocount on
PRINT 'Errorlogs'
PRINT '---------'
declare @i tinyint, @res int
set @i=0
while (@i<255) begin
if (0=@i) begin
print 'ERRORLOG'
exec @res=master.dbo.sp_readerrorlog
end else begin
print 'ERRORLOG.'+cast(@i as varchar(3))
exec @res=master.dbo.sp_readerrorlog @i
end
if (@@error<>0) OR (@res<>0) break
set @i=@i+1
end

Просмотреть файл

@ -176,18 +176,3 @@ ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT sqlserver.sql_tra
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT sqlserver.broker_corrupted_message ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT sqlserver.broker_forwarded_message_dropped ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT sqlserver.broker_message_undeliverable ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO

Просмотреть файл

@ -147,18 +147,3 @@ IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT sqlserver.broker_corrupted_message ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT sqlserver.broker_forwarded_message_dropped ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT sqlserver.broker_message_undeliverable ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO

Просмотреть файл

@ -0,0 +1,258 @@
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 0
BEGIN
PRINT ''
PRINT ' *** '
PRINT ' *** Skipped creating and configuring event session "xevent_SQLLogScout". Principal ' + SUSER_SNAME() + ' does not have ALTER ANY EVENT SESSION permission.'
PRINT ' *** To grant permissions, execute the following and rerun the script:'
PRINT ' *** '
PRINT ' *** GRANT ALTER ANY EVENT SESSION TO ' + QUOTENAME(SUSER_SNAME())
PRINT ' *** '
PRINT ''
END
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT ucs.ucs_change_notification ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT ucs.ucs_connection_corrupt_message ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT ucs.ucs_connection_flow_control ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT ucs.ucs_connection_recv_io ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT ucs.ucs_connection_recv_msg ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT ucs.ucs_connection_send_io ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT ucs.ucs_connection_send_msg ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT ucs.ucs_connection_setup ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT ucs.ucs_connection_state_machine ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT ucs.ucs_task_idempotent ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT ucs.ucs_task_periodic_work ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT ucs.ucs_transmitter_destination_connect ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT ucs.ucs_transmitter_destination_event ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT ucs.ucs_transmitter_destination_process ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT ucs.ucs_transmitter_destination_service ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT ucs.ucs_transmitter_periodic_work ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT ucs.ucs_transmitter_service_reclassify ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT ucs.ucs_transmitter_service_session ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT ucs.ucs_transmitter_stream_update ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT ucs.ucs_transport_periodic_work ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT sqlserver.broker_activation ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT sqlserver.broker_activation_stored_procedure_invoked ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT sqlserver.broker_activation_task_aborted ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT sqlserver.broker_activation_task_limit_reached ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT sqlserver.broker_activation_task_started ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT sqlserver.broker_conversation ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT sqlserver.broker_conversation_group ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT sqlserver.broker_corrupted_message ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT sqlserver.broker_dialog_transmission_body_dequeue ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT sqlserver.broker_dialog_transmission_body_enqueue ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT sqlserver.broker_dialog_transmission_queue_dequeue ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT sqlserver.broker_dialog_transmission_queue_enqueue ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT sqlserver.broker_forwarded_message_dropped ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT sqlserver.broker_forwarded_message_sent ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT sqlserver.broker_message_undeliverable ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT sqlserver.broker_mirrored_route_state_changed ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT sqlserver.broker_queue_activation_alert ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT sqlserver.broker_queue_disabled ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT sqlserver.broker_remote_message_acknowledgement ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT sqlserver.broker_transmission_acksm_action_fire ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT sqlserver.broker_transmission_acksm_event_begin ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT sqlserver.broker_transmission_acksm_event_end ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT sqlserver.broker_transmission_deliverysm_action_fire ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT sqlserver.broker_transmission_deliverysm_event_begin ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT sqlserver.broker_transmission_deliverysm_event_end ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT sqlserver.broker_transmission_exception ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT sqlserver.broker_transmission_object_get ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT ucs.ucs_transmitter_reclassify ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO
IF HAS_PERMS_BY_NAME(NULL, NULL, 'ALTER ANY EVENT SESSION') = 1
ALTER EVENT SESSION [xevent_SQLLogScout] ON SERVER ADD EVENT sqlserver.broker_message_classify ( ACTION (package0.event_sequence, sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.client_pid, sqlserver.database_id, sqlserver.database_name, sqlserver.is_system, sqlserver.nt_username, sqlserver.query_hash, sqlserver.request_id, sqlserver.server_principal_name, sqlserver.session_server_principal_name, sqlserver.session_id, sqlserver.session_nt_username, sqlserver.sql_text, sqlserver.transaction_id, sqlserver.username)
WHERE (([sqlserver].[client_hostname]<>N'sqllogscout') AND ([sqlserver].[client_hostname]<>N'sqllogscout_stop') AND ([sqlserver].[client_hostname]<>N'sqllogscout_cleanup'))
)
GO

Просмотреть файл

@ -42,8 +42,8 @@ IF [%6] EQU [] (set p6="") ELSE (set p6=%6)
IF [%7] EQU [] (set p7="") ELSE (set p7=%7)
IF [%8] EQU [] (set p8="") ELSE (set p8=%8)
powershell.exe -ExecutionPolicy RemoteSigned -File SQLLogScoutPs.ps1 -Scenario %p1% -ServerName %p2% -CustomOutputPath %p3% -DeleteExistingOrCreateNew %p4% -DiagStartTime %p5% -DiagStopTime %p6% -InteractivePrompts %p7% 2> .\##STDERR.LOG
REM always keep the -DisableCtrlCasInput as the last parameter in case future params are added
powershell.exe -ExecutionPolicy RemoteSigned -File SQLLogScoutPs.ps1 -Scenario %p1% -ServerName %p2% -CustomOutputPath %p3% -DeleteExistingOrCreateNew %p4% -DiagStartTime %p5% -DiagStopTime %p6% -InteractivePrompts %p7% -DisableCtrlCasInput %p8% 2> .\##STDERR.LOG
powershell.exe -ExecutionPolicy RemoteSigned -File StdErrorOutputHandling.ps1 .\##STDERR.LOG
@ -53,6 +53,9 @@ exit /b
:Help
@echo off
set cwd=%~dp0\Bin
cd "%cwd%"
powershell.exe -ExecutionPolicy RemoteSigned -File SQLLogScoutPs.ps1 -help
:EOF