Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save matthew-n/160cc5b8b1079989bac2c367926b2008 to your computer and use it in GitHub Desktop.
Save matthew-n/160cc5b8b1079989bac2c367926b2008 to your computer and use it in GitHub Desktop.
MY RED GATE SNIPPETS
These are my red gate snippets.
The powershell file "PushSnippets.ps1" is used to update them.
It can be modified so as to push your own snippets once you create a GIST for them.
<#
Author: Tim Cartwright
Purpose: To update / upload my snippets into a gist site. To use for your own snippets:
- Create a gist, and then grab the ID from the url.
- Modify the variable $gistId below with you gist id
- I prefix all my snippets with TDC. This script by design will only upload snippets that match that prefix. You can either
use your own prefix or remove the code that filters the snippets down to that prefix.
- OPTIONAL: modify the version of red gate to match yours where the snippets are located.
- RUN....
NOTES: I Had to install the github cli to authenticate with. TY Trevor R for figuring that out.
1) Install: https://cli.github.com/
2) From a command line run:
a) gh auth login
b) gh auth setup-git
#>
Clear-Host
########################################################################################################################
# EDIT THESE VALUES
########################################################################################################################
# my snippets prefix that I use, will only upload snippets that match this prefix
$snippetsPrefix = "TDC_"
# my gist id
$gistId = "6dbc79051ca756d71aef59371ba4e341"
# if the red gate version changes, or you use a custom path to your snippets, this path may need editing
$snippets = Get-ChildItem "$env:LOCALAPPDATA\Red Gate\" -Recurse -Filter "*.json" |
Where-Object {
$_.FullName -imatch "\\SQL Prompt \d{1,2}\\Snippets\\" -and `
$_.FullName -imatch "\\$snippetsPrefix.*?\.json"
}
########################################################################################################################
########################################################################################################################
$script = $MyInvocation.MyCommand.Source
$path = Split-Path $script -Parent
$env:GIT_REDIRECT_STDERR = '2>&1'
#https://stackoverflow.com/questions/6500880/with-git-how-do-i-turn-off-the-lf-will-be-replaced-by-crlf-warning
. git config --global core.safecrlf false
$clonePath = "$path\$gistId"
# we are not going to maintain the repo locally. we will clean it up before and after the script. That way we can just clone it each time
if (Test-Path $clonePath -PathType Container) {
Remove-Item $clonePath -Recurse -Force
}
# clone the repo to the local path
. git clone "https://gist.github.com/$gistId.git" $clonePath
# make a temp switch to the clone path
pushd $clonePath
# copy all snippets that match our prefix into the repo from the red gate snippets directory
$snippets | ForEach-Object { Copy-Item $_.FullName $clonePath -Force -Verbose }
# update the powershell in the repo from this one in case there have been any edits
Copy-Item $script $clonePath -Force
# add all the files recursively to the commit
. git add --all .
# commit
. git commit -m "Add / update snippets"
# If prompted, provide your Github credentials associated with the gist
# push back to the gists. may need to edit the main / master
. git push origin main
# revert back to the previous directory
popd
# make sure to clean up the repo directory one last time
if (Test-Path $clonePath -PathType Container) {
Remove-Item $clonePath -Recurse -Force
}
pause
{
"id": "e278d8d0-b6c2-4139-bd98-22901e26997e",
"prefix": "TDC_AddAppRoles",
"description": "",
"body": "DROP ROLE IF EXISTS [AppUser]\r\nDROP ROLE IF EXISTS [AppUserReadOnly]\r\n\r\nCREATE ROLE [AppUser]\r\nCREATE ROLE [AppUserReadOnly]\r\n\r\nDECLARE @sql VARCHAR(MAX) = ''\r\n\r\nSELECT @sql += CONCAT('\r\nGRANT EXECUTE, SELECT, INSERT, UPDATE, DELETE ON SCHEMA::', [s].[name], ' TO [AppUser]\r\nGRANT EXECUTE, SELECT ON SCHEMA::', [s].[name], ' TO [AppUserReadOnly]\r\n')\r\nFROM sys.[schemas] AS [s]\r\nWHERE s.[schema_id] = 1\r\n\tOR (s.[schema_id] > 4 AND s.[schema_id] < 16384)\r\n\r\nPRINT @sql\r\nEXEC (@sql)\r\n"
}
{
"id": "c3b22c13-8a57-435d-9f4a-b8169d8128f7",
"prefix": "TDC_AddCheckConstraint",
"description": "Add Check Constraint",
"status": "pendingShared",
"lastModified": "2022-11-11T16:27:54.0761526Z",
"permissions": [],
"body": "ALTER TABLE $schema_name$.$table_name$\n\tADD CONSTRAINT CK_$table_name$_$column_name$ \n\tCHECK ($column_name$ > 0)\nGO",
"placeholders": [
{
"name": "schema_name",
"defaultValue": "dbo"
},
{
"name": "table_name",
"defaultValue": ""
},
{
"name": "column_name",
"defaultValue": ""
}
]
}
{
"id": "e934490a-dd61-4780-87a1-903c52a98694",
"prefix": "TDC_AddColumn",
"description": "Add Column",
"status": "pendingShared",
"lastModified": "2022-11-11T16:27:54.0811647Z",
"permissions": [],
"body": "ALTER TABLE $schema_name$.$table_name$\n\tADD $column_name$ $data_type$ $null$ -- COLLATE $collate$\n\t-- CONSTRAINT DF_$table_name$_$column_name$ DEFAULT $value$\nGO",
"placeholders": [
{
"name": "schema_name",
"defaultValue": "dbo"
},
{
"name": "table_name",
"defaultValue": ""
},
{
"name": "column_name",
"defaultValue": ""
},
{
"name": "data_type",
"defaultValue": ""
},
{
"name": "null",
"defaultValue": ""
},
{
"name": "collate",
"defaultValue": "Latin1_General_CI_AS"
},
{
"name": "value",
"defaultValue": "''"
}
]
}
{
"id": "ca54d40e-f31a-44bd-9368-6d2241ad63cd",
"prefix": "TDC_AddExtendedProperty",
"description": "Add Description to a Specific Object.",
"status": "pendingShared",
"lastModified": "2022-11-11T16:27:54.0811647Z",
"permissions": [],
"body": "EXEC sys.sp_addextendedproperty --\n @name = N'$ExtPrp_Name$',\n @value = N'$ExtPrp_Value$',\n @level0type = N'$L0Type$', -- SCHEMA | FILEGROUP | USER | DDL TRIGGER | NULL\n @level0name = N'$L0Name$',\n @level1type = N'$L1Type$', -- TABLE | VIEW | FUNCTION | PROCEDURE | NULL\n @level1name = N'$L1Name$',\n @level2type = N'$L2Type$', -- COLUMN | CONSTRAINT | INDEX | PARAMETER | DML TRIGGER | NULL\n @level2name = N'$L2Name$';\nGO",
"placeholders": [
{
"name": "ExtPrp_Name",
"defaultValue": ""
},
{
"name": "ExtPrp_Value",
"defaultValue": ""
},
{
"name": "L0Type",
"defaultValue": ""
},
{
"name": "L0Name",
"defaultValue": ""
},
{
"name": "L1Type",
"defaultValue": ""
},
{
"name": "L1Name",
"defaultValue": ""
},
{
"name": "L2Type",
"defaultValue": ""
},
{
"name": "L2Name",
"defaultValue": ""
}
]
}
{
"id": "0ab374ec-02b6-4fd4-972c-ed73e2e7f63a",
"prefix": "TDC_AddPK",
"description": "Adding PrimaryKey to a Table",
"status": "pendingShared",
"lastModified": "2022-11-11T16:27:54.0821528Z",
"permissions": [],
"body": "IF OBJECT_ID('PK_$table_name$_$column_name$', 'PK') IS NOT NULL BEGIN\r\n\tALTER TABLE $schema_name$.$table_name$ DROP CONSTRAINT PK_$table_name$_$column_name$;\r\nEND\r\n\r\nALTER TABLE $schema_name$.$table_name$\r\n\tADD CONSTRAINT PK_$table_name$_$column_name$ \r\n\tPRIMARY KEY {CLUSTERED | NONCLUSTERED} ($column_name$);\r\nGO",
"placeholders": [
{
"name": "schema_name",
"defaultValue": null
},
{
"name": "table_name",
"defaultValue": null
},
{
"name": "column_name",
"defaultValue": null
}
]
}
{
"id": "2335709d-07a8-4063-a3cc-a70609fa39cd",
"prefix": "TDC_Admin_CheckServerOptions",
"description": "",
"status": "pendingShared",
"lastModified": "2022-11-11T16:27:54.0821528Z",
"permissions": [],
"body": "/*\r\n\tAuthor: Tim Cartwright\r\n\tPurpose: Allows you to check the server, and client SET options\r\n\thttps://docs.microsoft.com/en-us/sql/database-engine/configure-windows/configure-the-user-options-server-configuration-option\r\n\t1\tDISABLE_DEF_CNST_CHK\tControls interim or deferred constraint checking.\r\n\t2\tIMPLICIT_TRANSACTIONS\tFor dblib network library connections, controls whether a transaction is started implicitly when a statement is executed. The IMPLICIT_TRANSACTIONS setting has no effect on ODBC or OLEDB connections.\r\n\t4\tCURSOR_CLOSE_ON_COMMIT\tControls behavior of cursors after a commit operation has been performed.\r\n\t8\tANSI_WARNINGS\tControls truncation and NULL in aggregate warnings.\r\n\t16\tANSI_PADDING\tControls padding of fixed-length variables.\r\n\t32\tANSI_NULLS\tControls NULL handling when using equality operators.\r\n\t64\tARITHABORT\tTerminates a query when an overflow or divide-by-zero error occurs during query execution.\r\n\t128\tARITHIGNORE\tReturns NULL when an overflow or divide-by-zero error occurs during a query.\r\n\t256\tQUOTED_IDENTIFIER\tDifferentiates between single and double quotation marks when evaluating an expression.\r\n\t512\tNOCOUNT\tTurns off the message returned at the end of each statement that states how many rows were affected.\r\n\t1024\tANSI_NULL_DFLT_ON\tAlters the session's behavior to use ANSI compatibility for nullability. New columns defined without explicit nullability are defined to allow nulls.\r\n\t2048\tANSI_NULL_DFLT_OFF\tAlters the session's behavior not to use ANSI compatibility for nullability. New columns defined without explicit nullability do not allow nulls.\r\n\t4096\tCONCAT_NULL_YIELDS_NULL\tReturns NULL when concatenating a NULL value with a string.\r\n\t8192\tNUMERIC_ROUNDABORT\tGenerates an error when a loss of precision occurs in an expression.\r\n\t16384\tXACT_ABORT\tRolls back a transaction if a Transact-SQL statement raises a run-time error.\r\n*/\r\n\r\nDECLARE @options TABLE ([name] nvarchar(35), [minimum] int, [maximum] int, [config_value] int, [run_value] int)\r\nDECLARE @optionsCheck TABLE([id] int NOT NULL IDENTITY, [setting_name] varchar(128))\r\nDECLARE @current_value INT;\r\n\r\nINSERT INTO @options ([name], [minimum], [maximum], [config_value], [run_value])\r\nEXEC sp_configure 'user_options';\r\n\r\nSELECT @current_value = [config_value] FROM @options;\r\n\r\nINSERT INTO @optionsCheck \r\n\t([setting_name]) \r\nVALUES\r\n\t('DISABLE_DEF_CNST_CHK'),\r\n\t('IMPLICIT_TRANSACTIONS'),\r\n\t('CURSOR_CLOSE_ON_COMMIT'),\r\n\t('ANSI_WARNINGS'),\r\n\t('ANSI_PADDING'),\r\n\t('ANSI_NULLS'),\r\n\t('ARITHABORT'),\r\n\t('ARITHIGNORE'),\r\n\t('QUOTED_IDENTIFIER'),\r\n\t('NOCOUNT'),\r\n\t('ANSI_NULL_DFLT_ON'),\r\n\t('ANSI_NULL_DFLT_OFF'),\r\n\t('CONCAT_NULL_YIELDS_NULL'),\r\n\t('NUMERIC_ROUNDABORT'),\r\n\t('XACT_ABORT')\r\n\r\nSELECT fn.[value], \r\n\toc.[setting_name], \r\n\t[server_option] = CASE WHEN (@current_value & fn.[value]) = fn.[value] THEN 'ON' ELSE '-' END,\r\n\t[client_option] = CASE WHEN (@@options & fn.[value]) = fn.[value] THEN 'ON' ELSE '-' END\r\nFROM @optionsCheck oc\r\nCROSS APPLY (\r\n\tSELECT [value] = CASE WHEN oc.id > 1 THEN POWER(2, oc.id - 1) ELSE 1 END\r\n) fn"
}
{
"id": "33bf690a-912a-463b-873c-8b6d42fc90dc",
"prefix": "TDC_Admin_DiskLatency",
"description": "",
"status": "pendingShared",
"lastModified": "2022-11-11T16:27:54.0821528Z",
"permissions": [],
"body": "-- http://www.sqlskills.com/blogs/paul/how-to-examine-io-subsystem-latencies-from-within-sql-server/\r\n\r\nSELECT\r\n [ReadLatency] =\r\n CASE WHEN [num_of_reads] = 0\r\n THEN 0 ELSE ([io_stall_read_ms] / [num_of_reads]) END,\r\n [WriteLatency] =\r\n CASE WHEN [num_of_writes] = 0\r\n THEN 0 ELSE ([io_stall_write_ms] / [num_of_writes]) END,\r\n [Latency] =\r\n CASE WHEN ([num_of_reads] = 0 AND [num_of_writes] = 0)\r\n THEN 0 ELSE ([io_stall] / ([num_of_reads] + [num_of_writes])) END,\r\n [AvgBPerRead] =\r\n CASE WHEN [num_of_reads] = 0\r\n THEN 0 ELSE ([num_of_bytes_read] / [num_of_reads]) END,\r\n [AvgBPerWrite] =\r\n CASE WHEN [num_of_writes] = 0\r\n THEN 0 ELSE ([num_of_bytes_written] / [num_of_writes]) END,\r\n [AvgBPerTransfer] =\r\n CASE WHEN ([num_of_reads] = 0 AND [num_of_writes] = 0)\r\n THEN 0 ELSE\r\n (([num_of_bytes_read] + [num_of_bytes_written]) /\r\n ([num_of_reads] + [num_of_writes])) END,\r\n LEFT ([mf].[physical_name], 2) AS [Drive],\r\n DB_NAME ([vfs].[database_id]) AS [DB],\r\n [mf].[physical_name]\r\nFROM\r\n sys.dm_io_virtual_file_stats (NULL,NULL) AS [vfs]\r\nJOIN sys.master_files AS [mf]\r\n ON [vfs].[database_id] = [mf].[database_id]\r\n AND [vfs].[file_id] = [mf].[file_id]\r\n-- WHERE [vfs].[file_id] = 2 -- log files\r\n-- ORDER BY [Latency] DESC\r\n-- ORDER BY [ReadLatency] DESC\r\nORDER BY [WriteLatency] DESC;\r\nGO"
}
{
"id": "407a0e27-586d-42c5-81f2-5632aac347bd",
"prefix": "TDC_Admin_DropDiagramObjects",
"description": "",
"status": "pendingShared",
"lastModified": "2022-11-11T16:27:54.0831528Z",
"permissions": [],
"body": "-- REMOVE DATABASE DIAGRAMS OBJECTS FROM DB\r\n-- ***WARNING*** ANY EXISTING DIAGRAMS WILL GET DELETED IF YOU RUN THIS ***WARNING***\r\n\r\nIF OBJECT_ID('[dbo].[sp_upgraddiagrams]') IS NOT NULL BEGIN \r\n\tDROP PROC [dbo].[sp_upgraddiagrams]\r\nEND\r\n\r\nIF OBJECT_ID('[dbo].[sp_helpdiagrams]') IS NOT NULL BEGIN \r\n\tDROP PROC [dbo].[sp_helpdiagrams] \r\nEND\r\n\r\nIF OBJECT_ID('[dbo].[sp_helpdiagramdefinition]') IS NOT NULL BEGIN \r\n\tDROP PROC [dbo].[sp_helpdiagramdefinition] \r\nEND\r\n\r\nIF OBJECT_ID('[dbo].[sp_creatediagram]') IS NOT NULL BEGIN \r\n\tDROP PROC [dbo].[sp_creatediagram] \r\nEND\r\n\r\nIF OBJECT_ID('[dbo].[sp_renamediagram]') IS NOT NULL BEGIN \r\n\tDROP PROC [dbo].[sp_renamediagram] \r\nEND\r\n\r\nIF OBJECT_ID('[dbo].[sp_alterdiagram]') IS NOT NULL BEGIN \r\n\tDROP PROC [dbo].[sp_alterdiagram] \r\nEND\r\n\r\nIF OBJECT_ID('[dbo].[sp_dropdiagram]') IS NOT NULL BEGIN \r\n\tDROP PROC [dbo].[sp_dropdiagram] \r\nEND\r\n\r\nIF OBJECT_ID('[dbo].[fn_diagramobjects]') IS NOT NULL BEGIN \r\n\tDROP FUNCTION [dbo].[fn_diagramobjects] \r\nEND\r\n\r\nIF OBJECT_ID('[dbo].[sysdiagrams]') IS NOT NULL BEGIN \r\n\tDROP TABLE [dbo].[sysdiagrams] \r\nEND\r\n\r\nIF OBJECT_ID('[dbo].[dt_properties]') IS NOT NULL BEGIN \r\n\tDROP TABLE [dbo].[dt_properties] \r\nEND"
}
{
"id": "a8557ded-d3f9-4b7d-a0f2-a27abb2c5eaa",
"prefix": "TDC_Admin_FindAndFixNonDBOSchemas",
"description": "",
"status": "pendingShared",
"lastModified": "2022-11-17T16:07:19.8451999Z",
"permissions": [],
"body": "DECLARE @sql NVARCHAR(MAX) = N''\r\n\r\nSELECT @sql += N'ALTER AUTHORIZATION ON SCHEMA::[' + s.name + N'] TO dbo;' + NCHAR(13) + NCHAR(10)\r\nFROM sys.schemas s \r\nWHERE s.schema_id > 4 \r\n\tAND s.schema_id < 16384\r\n\tAND s.[principal_id] > 10\r\n\r\nPRINT @sql\r\nEXEC (@sql)\r\n"
}
{
"id": "0b91a55c-d37a-4f8e-a35f-54760de890fa",
"prefix": "TDC_Admin_FindColumnsWithDiffTypes",
"description": "",
"status": "pendingShared",
"lastModified": "2022-11-17T16:07:19.8462766Z",
"permissions": [],
"body": "SELECT DISTINCT c.[Name], TypeName = TYPE_NAME(c.[system_type_id]), c.[max_length] \r\nFROM sys.[columns] c\r\nINNER JOIN sys.[columns] c2 \r\n\tON [c].[name] = [c2].[name]\r\n\tAND OBJECTPROPERTY(c.[object_id], 'IsMsShipped') = 0\r\n\tAND OBJECTPROPERTY(c2.[object_id], 'IsMsShipped') = 0\r\n\tAND (c.[system_type_id] <> c2.[system_type_id] \r\n\t\tOR c.[max_length] <> c2.[max_length])\r\nINNER JOIN sys.[tables] t \r\n\tON [c].[object_id] = [t].[object_id] \r\n\tOR c2.[object_id] = t.[object_id]\r\nORDER BY c.[name], TYPE_NAME(c.[system_type_id]), c.[max_length]"
}
{
"id": "b7fb0f22-19d2-49fa-adf8-2d3ab62d15ce",
"prefix": "TDC_Admin_FindIndentityPKsWithFillFactor",
"description": "",
"status": "pendingShared",
"lastModified": "2022-11-17T16:07:19.8462766Z",
"permissions": [],
"body": "-- FIND ALL PRIMARY KEYS WHERE THE FIRST COLUMN IS AN IDENTITY AND THE FILL FACTOR ADDS EMPTY SPACE\r\n\r\nSELECT [db_name] = DB_NAME(),\r\n\t[schema_name] = OBJECT_SCHEMA_NAME(i.[object_id], DB_ID()),\r\n\t[table_name] = OBJECT_NAME(i.[object_id]), \r\n\t[index_name] = [i].Name, \r\n\t[i].[type_desc], \r\n\t[i].[fill_factor], \r\n\t[ic].[index_column_id], \r\n\t[ic].[key_ordinal], \r\n\t[c].[is_identity],\r\n\t[index_in_row_size_in_mb] = CAST(fn1.[IndexInRowSizeInMB] AS money),\r\n\t[index_in_row_empty_mb] = CAST(fn2.[IndexInRowEmptyMB] AS money),\r\n\t[index_lob_size_in_mb] = CAST(fn1.[IndexLOBSizeInMB] AS money),\r\n\tddps.[row_count]\r\nFROM sys.[indexes] i \r\nINNER JOIN sys.[dm_db_partition_stats] ddps ON [ddps].[index_id] = [i].[index_id] AND [ddps].[object_id] = [i].[object_id] \r\nINNER JOIN sys.[index_columns] ic ON [i].[object_id] = [ic].[object_id] AND [i].[index_id] = [ic].[index_id] AND [ic].[key_ordinal] = 1\r\nINNER JOIN sys.[columns] c ON [i].[object_id] = [c].[object_id] AND [ic].[column_id] = [c].[column_id]\r\nCROSS APPLY (\r\n\tSELECT [IndexInRowSizeInMB] = ddps.[in_row_data_page_count] / 128.0, \r\n\t\t[IndexLOBSizeInMB] = ddps.[lob_used_page_count] / 128.0\r\n) fn1\r\nCROSS APPLY (\r\n\tSELECT [IndexInRowEmptyMB] = fn1.[IndexInRowSizeInMB] * (1 - (i.[fill_factor] / 100.0))\r\n) fn2\r\nWHERE [i].[type] = 1 -- clustered\r\n\tAND [ic].[key_ordinal] = 1 -- first column in pk\r\n\tAND [c].[is_identity] = 1 \r\n\tAND ([i].[fill_factor] > 0 AND [i].[fill_factor] < 100)"
}
{
"id": "bf8b148a-bb6f-449a-845d-c5e2a21dbd10",
"prefix": "TDC_Admin_GenerateAlerts",
"description": "",
"status": "pendingShared",
"lastModified": "2022-11-17T16:07:19.8462766Z",
"permissions": [],
"body": "/* \r\n\tRewrite from here: https://www.brentozar.com/blitz/configure-sql-server-alerts/ \r\n\tMore info (shows available tokens): \r\n\t\thttps://www.simple-talk.com/sql/database-administration/sql-server-alerts-soup-to-nuts/\r\n\t\thttp://tomaslind.net/2016/11/04/sql-agent-logging-tokens/\r\n*/\r\nSET NOCOUNT ON\r\nUSE [msdb]\r\nGO\r\n\r\n-- Configure these lines: \r\nDECLARE @operator_name sysname = N'$operator_name$',\r\n\t@emails nvarchar(4000) = N'$emails$',\r\n\t@pagers nvarchar(4000) = N'$pagers$'\r\n\r\n-- loop variables\r\nDECLARE @alert_name sysname = NULL,\r\n\t@severity int = 0,\r\n\t@message_id int = 0,\r\n\t@message nvarchar(max) = NULL,\r\n\t@performance_condition nvarchar(max) = NULL\r\n\r\nDECLARE @alerts TABLE (\r\n\t[name] sysname NOT NULL,\r\n\t[severity] int NOT NULL,\r\n\t[message_id] int NOT NULL,\r\n\t[performance_condition] nvarchar(max) NULL,\r\n\t[message] nvarchar(max) NULL\r\n)\r\n\r\n-- configure add new alerts, use existing templates as examples.\r\n-- Only one of the following Severity, Message_Id, OR [performance_condition] can be supplied. \r\nINSERT INTO @alerts ( [name], [severity], [message_id], [performance_condition], [message] )\r\nVALUES \r\n\t-- Severities, message id must == 0, and performance_condition must be null\r\n\t( N'Severity 016', 16, 0, NULL, NULL ),\r\n\t( N'Severity 017', 17, 0, NULL, NULL ),\r\n\t( N'Severity 018', 18, 0, NULL, NULL ),\r\n\t( N'Severity 019', 19, 0, NULL, NULL ),\r\n\t( N'Severity 020', 20, 0, NULL, NULL ),\r\n\t( N'Severity 021', 21, 0, NULL, NULL ),\r\n\t( N'Severity 022', 22, 0, NULL, NULL ),\r\n\t( N'Severity 023', 23, 0, NULL, NULL ),\r\n\t( N'Severity 024', 24, 0, NULL, NULL ),\r\n\t( N'Severity 025', 25, 0, NULL, NULL ),\r\n\t-- performance counter alerts, severity must == 0, and message id must == 0\r\n\t( N'PLE Alert', 0, 0, N'Buffer Manager|Page life expectancy||<|45', N'Page Life Expectancy has fallen under 45 seconds' ),\r\n\t-- error number alerts, severity must == 0, and performance_condition must be null\r\n\t( N'Error Number 823', 0, 823, NULL, NULL ),\r\n\t( N'Error Number 824', 0, 824, NULL, NULL ),\r\n\t( N'Error Number 825', 0, 825, NULL, NULL ),\r\n\t( N'Error Number 9002', 0, 9002, NULL, N'Error 9002, the transaction log for database $(ESCAPE_SQUOTE(A-DBN)) is full due to ''LOG_BACKUP''.'),\r\n\t( N'Error Number 5901', 0, 5901, NULL, N'One or more recovery units belonging to database $(ESCAPE_SQUOTE(A-DBN)) failed to generate a checkpoint.' ),\r\n\t( N'Error Number 1101', 0, 1101, NULL, N'Error 1101 has been encountered which signifies a database has run out of file space. ERROR (1101) this alert is supposed to be triggered on: Could not allocate a new page for database $(ESCAPE_SQUOTE(A-DBN)) because of insufficient disk space in filegroup ''PRIMARY''. ' ),\r\n\t( N'Error Number 1105', 0, 1105, NULL, N'Error 1105 has been encountered which signifies a database has run out of file space. Example of the error (1105) this alert is supposed to be triggred on: Could not allocate space for object \"<db_object>\" in database $(ESCAPE_SQUOTE(A-DBN)) because the ''PRIMARY'' filegroup is full. ')\r\n\r\n\r\n\r\nIF EXISTS(SELECT 1 FROM [dbo].[sysoperators] s WHERE s.[name] = @operator_name) BEGIN\r\n\tEXEC msdb.dbo.sp_delete_operator @name=@operator_name\r\nEND\r\n\r\nEXEC msdb.dbo.sp_add_operator @name=@operator_name, \r\n\t\t@enabled=1, \r\n\t\t@weekday_pager_start_time=000000, \r\n\t\t@weekday_pager_end_time=235959, \r\n\t\t@saturday_pager_start_time=000000, \r\n\t\t@saturday_pager_end_time=235959, \r\n\t\t@sunday_pager_start_time=000000, \r\n\t\t@sunday_pager_end_time=235959, \r\n\t\t@pager_days=127, \r\n\t\t@email_address=@emails, \r\n\t\t@pager_address=@pagers, \r\n\t\t@category_name=N'[Uncategorized]'\r\n\r\n--SELECT * FROM [dbo].[sysalerts] s\r\nWHILE EXISTS (SELECT TOP 1 a.[name] FROM @alerts a) BEGIN\r\n\t-- get the alert name to work on\r\n\tSELECT TOP 1 @alert_name = a.[name], @severity = [a].[severity], @message_id = [a].[message_id], @performance_condition = [performance_condition], @message = [message] \r\n\tFROM @alerts a\r\n\t\r\n\tPRINT CHAR(10) + 'WORKING ON ' + @alert_name\r\n\r\n\t-- try to find the alert that matches by name OR ( by message id || by severity || by performance condition )\r\n\tDECLARE @tmpAlertName sysname = (\r\n\t\tSELECT TOP 1 s.[name] \r\n\t\tFROM [dbo].[sysalerts] s \r\n\t\tWHERE [s].[name] = @alert_name \r\n\t\t\tOR s.[message_id] = CASE WHEN @message_id = 0 THEN NULL ELSE @message_id END\r\n\t\t\tOR s.[severity] = CASE WHEN @severity = 0 THEN NULL ELSE @severity END\r\n\t\t\tOR s.[performance_condition] = ISNULL(@performance_condition, 'NOT SET')\r\n\t)\r\n\r\n\t-- drop the alert if exists\r\n\tIF @tmpAlertName IS NOT NULL BEGIN\r\n\t\tPRINT 'DROPPING ' + @tmpAlertName\r\n\t\tEXEC msdb.dbo.sp_delete_alert @name = @tmpAlertName\r\n\tEND\r\n\r\n\tPRINT 'ADDING ' + @alert_name\r\n\t-- add the alert\r\n\tEXEC msdb.dbo.sp_add_alert @name=@alert_name,\r\n\t\t@message_id=@message_id,\r\n\t\t@severity=@severity,\r\n\t\t@enabled=1,\r\n\t\t@delay_between_responses=600,\r\n\t\t@include_event_description_in=1,\r\n\t\t@job_id=N'00000000-0000-0000-0000-000000000000',\r\n\t\t@performance_condition = @performance_condition,\r\n\t\t@notification_message = @message;\r\n\t-- add the notification\r\n\tEXEC msdb.dbo.sp_add_notification @alert_name=@alert_name, @operator_name=@operator_name, @notification_method = 3;\r\n\t\r\n\tDELETE TOP (1) FROM @alerts WHERE [name] = @alert_name\r\nEND",
"placeholders": [
{
"name": "operator_name",
"defaultValue": "SQL_Alerts"
},
{
"name": "emails",
"defaultValue": "[email protected]"
},
{
"name": "pagers",
"defaultValue": "[email protected]"
}
]
}
{
"id": "21ec0ccb-204c-4678-add8-14db69aa31e0",
"prefix": "TDC_Admin_GenerateForeignKeysDropAndReCreateStatements",
"description": "To Generate Drop and ReCreate Statements of ALL Foreign Keys in a Given Database",
"status": "pendingShared",
"lastModified": "2022-11-17T16:07:19.8462766Z",
"permissions": [],
"body": "/* =================================================================================================\r\n-- Script\t\t: Generate_ForeignKey_Constraints_Drop_And_Create_Statements.sql\r\n-- Description\t: To Generate Drop and Create Statements for ALL Foreign Keys Constraints.\r\n-- Server\t\t: LOCALSERVER\r\n-- Database\t\t: USER Database\r\n================================================================================================= */\r\nSELECT --\r\n\tFK.NAME AS CONSTRAINT_NAME,\r\n\t--$BeginRegion: Generate Drop Foreign Keys Statements\r\n\t'IF OBJECT_ID(''' + QUOTENAME(OBJECT_SCHEMA_NAME(FK.parent_object_id)) + '.' + QUOTENAME(FK.NAME) + ''', ''F'') IS NOT NULL'\r\n\t\t+ ' ALTER TABLE ' + QUOTENAME(OBJECT_SCHEMA_NAME(FK.parent_object_id)) + '.' + QUOTENAME(OBJECT_NAME(FK.parent_object_id))\r\n\t\t+ ' DROP CONSTRAINT ' + QUOTENAME(FK.NAME)\r\n\t\t+ ';' \r\n\t\tAS \"DROP_CONSTRAINT_STATEMENT\",\r\n\t--$EndRegion: Generate Drop Foreign Keys Statements\r\n\t--\r\n\t--$BeginRegion: Generate ReCreate Foreign Keys Statements\r\n\t'IF OBJECT_ID(''' + QUOTENAME(OBJECT_SCHEMA_NAME(FK.parent_object_id)) + '.' + QUOTENAME(FK.NAME) + ''', ''F'') IS NULL'\r\n\t\t+ ' BEGIN'\r\n\t\t+ ' ALTER TABLE ' + QUOTENAME(OBJECT_SCHEMA_NAME(FK.parent_object_id)) + '.' + QUOTENAME(OBJECT_NAME(FK.parent_object_id))\r\n\t\t+ ' WITH ' + CASE FK.is_not_trusted WHEN 0 THEN 'CHECK' ELSE 'NOCHECK' END\r\n\t\t+ ' ADD CONSTRAINT ' + QUOTENAME(OBJECT_NAME(FK.object_id))\r\n\t\t+ ' FOREIGN KEY'\r\n\t\t+ ' (' + STUFF((SELECT ', ' + QUOTENAME(C.NAME)\r\n\t\t\t\t\t\tFROM sys.columns AS C\r\n\t\t\t\t\t\tINNER JOIN sys.foreign_key_columns AS KC ON C.object_id = KC.parent_object_id AND C.column_id = KC.parent_column_id\r\n\t\t\t\t\t\tWHERE KC.constraint_object_id = FK.object_id\r\n\t\t\t\t\t\tORDER BY KC.constraint_column_id FOR XML PATH('')), 1, 1, '') + ' )'\r\n\t\t+ ' REFERENCES ' + QUOTENAME(OBJECT_SCHEMA_NAME(FK.referenced_object_id)) + '.' + QUOTENAME(OBJECT_NAME(FK.referenced_object_id))\r\n\t\t+ ' (' + STUFF((SELECT ', ' + QUOTENAME(C.NAME)\r\n\t\t\t\t\t\tFROM sys.columns AS C\r\n\t\t\t\t\t\tINNER JOIN sys.foreign_key_columns AS KC ON C.object_id = KC.referenced_object_id AND C.column_id = KC.referenced_column_id\r\n\t\t\t\t\t\tWHERE KC.constraint_object_id = FK.object_id\r\n\t\t\t\t\t\tORDER BY KC.constraint_column_id FOR XML PATH('')), 1, 1, '') + ' )'\r\n\t\t+ ' ON DELETE ' + CASE FK.delete_referential_action WHEN 1 THEN 'CASCADE' WHEN 2 THEN 'SET NULL' WHEN 3 THEN 'SET DEFAULT' ELSE 'NO ACTION' END\r\n\t\t+ ' ON UPDATE ' + CASE FK.update_referential_action WHEN 1 THEN 'CASCADE' WHEN 2 THEN 'SET NULL' WHEN 3 THEN 'SET DEFAULT' ELSE 'NO ACTION' END\r\n\t\t+ CASE FK.is_not_for_replication WHEN 0 THEN '' ELSE ' NOT FOR REPLICATION' END\r\n\t\t+ ';'\r\n\t\t+ ' ALTER TABLE ' + QUOTENAME(OBJECT_SCHEMA_NAME(FK.parent_object_id)) + '.' + QUOTENAME(OBJECT_NAME(FK.parent_object_id))\r\n\t\t+ CASE FK.is_disabled WHEN 0 THEN ' CHECK' ELSE ' NOCHECK' END + ' CONSTRAINT ' + QUOTENAME(OBJECT_NAME(FK.object_id))\r\n\t\t+ ';'\r\n\t\t+ ' END'\r\n\t\tAS \"RECREATE_CONSTRAINT_STATEMENT\"\r\n\t--$EndRegion: Generate ReCreate Foreign Keys Statements\r\nFROM sys.foreign_keys AS FK\r\nWHERE FK.is_ms_shipped = 0\r\nORDER BY OBJECT_SCHEMA_NAME(FK.parent_object_id), OBJECT_NAME(FK.parent_object_id), FK.name ASC;"
}
{
"id": "099d1a92-097c-4866-8e79-84df22706f23",
"prefix": "TDC_Admin_GetAGListenerNameOrServerName",
"description": "",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.977685Z",
"permissions": [],
"body": "SELECT ISNULL((\r\n\tSELECT dns_name + '\\' + CAST(SERVERPROPERTY ('InstanceName') AS VARCHAR(512))\r\n\tFROM sys.availability_group_listeners agl\r\n\tJOIN sys.availability_group_listener_ip_addresses aglip\r\n\t\tON agl.listener_id = aglip.listener_id\r\n\tJOIN sys.dm_exec_connections c\r\n\t\tON aglip.ip_address = c.local_net_address\r\n\tWHERE session_id = @@SPID\r\n), @@SERVERNAME)"
}
{
"id": "a188200e-c185-4c86-9c2a-32d3449dc998",
"prefix": "TDC_Admin_GetAutoGrowthEventsOccured",
"description": "Get Database Files \"Growth and Shrink\" Events from Instance Log File",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.977685Z",
"permissions": [],
"body": "DECLARE @logtrace_path NVARCHAR(260);\r\nSELECT @logtrace_path = REVERSE(SUBSTRING(REVERSE(path), CHARINDEX(CHAR(92), REVERSE(path)), 260)) + N'log.trc'\r\nFROM sys.traces WHERE is_default = 1;\r\n\r\n-- process all trace files\r\nSELECT TraceLog.StartTime,\r\n\t TraceEvents.name AS \"EventName\",\r\n\t DB_NAME(TraceLog.databaseid) AS \"DatabaseName\",\r\n\t TraceLog.Filename,\r\n\t (TraceLog.IntegerData * 8) / 1024.0 AS \"Growth(MB)\",\r\n\t (TraceLog.duration / 1000) AS \"Duration(msec)\"\r\nFROM::fn_trace_gettable(@logtrace_path, DEFAULT) AS TraceLog\r\nINNER JOIN sys.trace_events AS TraceEvents\r\n\tON TraceLog.EventClass = TraceEvents.trace_event_id\r\nWHERE TraceLog.EventClass IN ( --\r\n\t\t\t\t\t\t\t\t 92, -- Data File Auto Expand\r\n\t\t\t\t\t\t\t\t 93, -- Log File Auto Expand\r\n\t\t\t\t\t\t\t\t 94, -- Data File Auto Shrink\r\n\t\t\t\t\t\t\t\t 95\t -- Log File Auto Shrink\r\n\t\t\t\t\t\t\t )\r\n\t AND DB_NAME(TraceLog.databaseid) = DB_NAME()\r\nORDER BY TraceLog.StartTime;"
}
{
"id": "ea88e27d-5cdc-4677-8a1b-17cd3a3f6927",
"prefix": "TDC_Admin_GetBlockChain",
"description": "",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.977685Z",
"permissions": [],
"body": "-- https://www.techrepublic.com/blog/the-enterprise-cloud/find-blocking-processes-using-recursion-in-sql-server-2005/\r\n-- TIM C: \r\n-- 1) Modified the query so as not to return multiple sets for each block \r\n-- 2) Switched to using dm_exec_requests \r\n\r\nIF OBJECT_ID('tempdb..#Processes') IS NOT NULL BEGIN \r\n DROP TABLE #Processes \r\nEND\r\n\r\nCREATE TABLE #processes (\r\n spid SMALLINT NOT NULL, \r\n blocking_spid SMALLINT NOT NULL,\r\n database_name sysname NOT NULL,\r\n program_name sysname NULL,\r\n login_name sysname NOT NULL,\r\n start_time DATETIME NOT NULL,\r\n object_name sysname NULL,\r\n definition NVARCHAR(MAX) NULL\r\n)\r\n\r\nINSERT INTO #processes (\r\n spid,\r\n blocking_spid,\r\n database_name,\r\n program_name,\r\n login_name,\r\n start_time,\r\n object_name,\r\n definition\r\n)\r\nSELECT spid = der.session_id, \r\n blocking_spid = der.blocking_session_id,\r\n database_name = DB_NAME(der.database_id), \r\n des.program_name,\r\n des.login_name,\r\n der.start_time,\r\n object_name = OBJECT_NAME(dest.objectid, der.database_id),\r\n definition = dest.text\r\nFROM sys.dm_exec_requests der\r\nINNER JOIN sys.dm_exec_sessions des \r\n ON des.session_id = der.session_id\r\nOUTER APPLY sys.dm_exec_sql_text(der.sql_handle) dest\r\nWHERE der.session_id > 50\r\n\r\n;WITH Blocking AS (\r\n SELECT s.spid,\r\n s.database_name, \r\n s.program_name, \r\n s.login_name,\r\n s.blocking_spid,\r\n s.start_time,\r\n s.definition,\r\n block_chain = ROW_NUMBER() OVER (ORDER BY s.spid),\r\n 1 AS block_chain_link\r\n FROM #Processes s\r\n WHERE s.blocking_spid = 0\r\n AND EXISTS (\r\n SELECT 1 \r\n FROM #Processes s1 \r\n WHERE s1.blocking_spid = s.spid\r\n )\r\n UNION ALL\r\n SELECT r.spid,\r\n r.database_name,\r\n r.program_name, \r\n r.login_name,\r\n r.blocking_spid,\r\n r.start_time,\r\n r.definition,\r\n d.block_chain,\r\n d.block_chain_link + 1\r\n FROM #Processes r\r\n INNER JOIN Blocking d\r\n ON r.blocking_spid = d.SPID\r\n WHERE r.blocking_spid > 0\r\n)\r\n\r\nSELECT b.spid,\r\n b.blocking_spid,\r\n b.database_name,\r\n b.program_name,\r\n b.login_name,\r\n b.start_time,\r\n b.definition,\r\n b.block_chain,\r\n b.block_chain_link\r\nFROM Blocking b\r\nORDER BY b.block_chain, \r\n b.block_chain_link, \r\n b.spid;"
}
{
"id": "53991c00-0ad4-4bef-9d80-dd78d5bddd68",
"prefix": "TDC_Admin_GetBufferPoolPagesPerDB",
"description": "",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9786853Z",
"permissions": [],
"body": "SELECT [cached_pages_count] = COUNT(*),\r\n\t [cached_pages_count_mb] = CAST(COUNT(*) / 128.0 AS money),\r\n\t [database_name] = CASE dobd.[database_id]\r\n\t\t WHEN 32767 THEN 'ResourceDb'\r\n\t\t ELSE DB_NAME([database_id])\r\n\t END \r\nFROM [sys].[dm_os_buffer_descriptors] dobd\r\nGROUP BY dobd.[database_id]\r\nORDER BY [cached_pages_count] DESC;"
}
{
"id": "82e6669a-4b5c-4a67-9a16-9a482405182c",
"prefix": "TDC_Admin_GetDatabaseSpaceUsedByTables",
"description": "Get Database Space Used By Tables and RowCount",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9786853Z",
"permissions": [],
"body": ";WITH DTS --DetailedTableSize\r\nAS (\r\n\t --$BeginRegion: TablePartitionStats\r\n\t SELECT DDPS.object_id,\r\n\t\t\t SUM(IIF((DDPS.index_id < 2), DDPS.row_count, 0)) AS \"Rows\",\r\n\t\t\t SUM(DDPS.reserved_page_count) AS \"ReservedPages\",\r\n\t\t\t SUM(DDPS.used_page_count) AS \"UsedPages\",\r\n\t\t\t SUM(IIF((DDPS.index_id < 2), (DDPS.in_row_data_page_count + DDPS.lob_used_page_count + DDPS.row_overflow_used_page_count), 0)) AS \"Pages\"\r\n\t FROM sys.dm_db_partition_stats AS DDPS\r\n\t WHERE OBJECT_SCHEMA_NAME(DDPS.object_id) <> 'sys'\r\n\t GROUP BY DDPS.object_id\r\n\t --$EndRegion: TablePartitionStats\r\n\t UNION ALL\r\n\r\n\t --$BeginRegion: InternalTablePartitionStats\r\n\t SELECT IT.parent_id AS \"object_id\",\r\n\t\t\t 0 AS \"Rows\",\r\n\t\t\t SUM(DDPS.reserved_page_count) AS \"ReservedPages\",\r\n\t\t\t SUM(DDPS.used_page_count) AS \"UsedPages\",\r\n\t\t\t 0 AS \"pages\"\r\n\t FROM sys.dm_db_partition_stats AS DDPS\r\n\t INNER JOIN sys.internal_tables AS IT\r\n\t\t ON DDPS.object_id = IT.object_id\r\n\t WHERE IT.internal_type IN ( 202, 204, 207, 211, 212, 213, 214, 215, 216, 221, 222, 236 )\r\n\t GROUP BY IT.parent_id\r\n --$EndRegion: InternalTablePartitionStats\r\n )\r\nSELECT OBJECT_SCHEMA_NAME(DTS.object_id) AS \"SchemaName\",\r\n\t OBJECT_NAME(DTS.object_id) AS \"TableName\",\r\n\t SUM(DTS.Rows) AS \"RowCount\",\r\n\t SUM(DTS.ReservedPages) * 8 AS \"Reserved(kB)\",\r\n\t SUM(DTS.Pages) * 8 AS \"Data(kB)\",\r\n\t IIF((SUM(DTS.UsedPages) > SUM(DTS.Pages)), (SUM(DTS.UsedPages) - SUM(DTS.Pages)), 0) * 8 AS \"Index(kB)\",\r\n\t IIF((SUM(DTS.ReservedPages) > SUM(DTS.UsedPages)), (SUM(DTS.ReservedPages) - SUM(DTS.UsedPages)), 0) * 8 AS \"UnUsed(kB)\",\r\n\t EP.value AS \"Comments\"\r\nFROM DTS\r\nINNER JOIN sys.tables AS T\r\n\tON T.object_id = DTS.object_id\r\nLEFT JOIN sys.extended_properties AS EP\r\n\tON T.object_id = EP.major_id AND (EP.name = 'MS_Description' AND EP.minor_id = 0 AND EP.class_desc = 'OBJECT_OR_COLUMN')\r\nGROUP BY DTS.object_id, EP.value\r\nORDER BY SchemaName, TableName ASC;"
}
{
"id": "54c77cb0-e1e8-41e4-a6b9-c04eecfe0be2",
"prefix": "TDC_Admin_GetDeadlocksInfoAndAnalyse",
"description": "Analyze Deadlocks From XML file(s), Trace",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9786853Z",
"permissions": [],
"body": "/* =========================================================================================================================================\r\n-- Server\t\t: LOCAL SERVER\r\n-- Database\t\t: TempDB (Preferred)\r\n-- Script\t\t: GetDeadlocksInfoAndAnalyse\r\n-- Description\t: Analyze Deadlocks From XML file(s), Trace\r\n-- Usage\t\t: Define DeadLock XML File at 'C:\\SQL\\Deadlocks\\DeadLock001.xml'.\r\n--\t\t\t\t\tWe Can Append Multiple XML Files using UNION ALL(NOT UNION).\r\n-- Link\t\t\t: https://blog.waynesheffield.com/wayne/code-library/deadlocks/shred-deadlock-graph/\r\n-- History\t\t:\r\n========================================================================================================================================= */\r\nDECLARE @DeadLockXMLs TABLE\r\n(\r\n\tDeadlockID INT IDENTITY PRIMARY KEY CLUSTERED,\r\n\tDeadlockGraph XML NULL\r\n);\r\n--\r\nINSERT INTO @DeadLockXMLs (DeadlockGraph)\r\nSELECT CONVERT(XML, BulkColumn, 2) FROM OPENROWSET(BULK '$DeadLockFilePath$\\$DeadLockFileName$.xml', SINGLE_BLOB) AS rowsetresults\r\n--UNION ALL \r\n--SELECT CONVERT(XML, BulkColumn, 2) FROM OPENROWSET(BULK 'C:\\SQL\\Deadlocks\\DeadLock002.xml', SINGLE_BLOB) AS rowsetresults;\r\n--\r\n/* ===== ** DO NOT CHANGE CODE BELOW FROM HERE ** ======================================================================================= */\r\n;\r\nWITH _DeadLocks\r\nAS (\r\n\t SELECT DeadlockID,\r\n\t\t\t DeadlockGraph\r\n\t FROM @DeadLockXMLs\r\n ),\r\n_Victims\r\nAS (\r\n\t SELECT Victims.List.value('@id', 'varchar(50)') AS \"ID\"\r\n\t FROM _DeadLocks AS CTE\r\n\t CROSS APPLY CTE.DeadlockGraph.nodes('//deadlock/victim-list/victimProcess') AS Victims(LIST)\r\n ),\r\n_Locks\r\nAS (\t-- Merge All of The Lock Information Together\r\n\t SELECT CTE.DeadlockID,\r\n\t\t\t MainLock.Process.value('@id', 'varchar(100)') AS \"LockID\",\r\n\t\t\t OwnerList.Owner.value('@id', 'varchar(200)') AS \"LockProcessId\",\r\n\t\t\t REPLACE(MainLock.Process.value('local-name(.)', 'varchar(100)'), 'lock', '') AS \"LockEvent\",\r\n\t\t\t MainLock.Process.value('@objectname', 'sysname') AS \"ObjectName\",\r\n\t\t\t OwnerList.Owner.value('@mode', 'varchar(10)') AS \"LockMode\",\r\n\t\t\t MainLock.Process.value('@dbid', 'INTEGER') AS \"Database_id\",\r\n\t\t\t MainLock.Process.value('@associatedObjectId', 'BIGINT') AS \"AssociatedObjectId\",\r\n\t\t\t MainLock.Process.value('@WaitType', 'varchar(100)') AS \"WaitType\",\r\n\t\t\t WaiterList.Owner.value('@id', 'varchar(200)') AS \"WaitProcessId\",\r\n\t\t\t WaiterList.Owner.value('@mode', 'varchar(10)') AS \"WaitMode\"\r\n\t FROM _DeadLocks AS CTE\r\n\t CROSS APPLY CTE.DeadlockGraph.nodes('//deadlock/resource-list') AS Lock(list)\r\n\t CROSS APPLY Lock.list.nodes('*') AS MainLock(Process)\r\n\t OUTER APPLY MainLock.Process.nodes('owner-list/owner') AS OwnerList(Owner)\r\n\t CROSS APPLY MainLock.Process.nodes('waiter-list/waiter') AS WaiterList(Owner)\r\n ),\r\n_Process\r\nAS (\t-- Get the Data from the Process Node\r\n\t SELECT CTE.DeadlockID,\r\n\t\t\t CONVERT(BIT, CASE WHEN Deadlock.Process.value('@id', 'varchar(50)') = ISNULL(Deadlock.Process.value('../../@victim', 'varchar(50)'), V.ID) THEN 1 ELSE 0 END) AS \"Victim\",\r\n\t\t\t Deadlock.Process.value('@lockMode', 'varchar(10)') AS \"LockMode\",\t\t\t\t\t\t-- how is this different from in the resource-list section?\r\n\t\t\t Process.ID AS \"ProcessID\",\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t-- Deadlock.Process.value('@id', 'varchar(50)'),\r\n\t\t\t Deadlock.Process.value('@kpid', 'int') AS \"KPID\",\t\t\t\t\t\t\t\t\t\t-- kernel-process id / thread ID number\r\n\t\t\t Deadlock.Process.value('@spid', 'int') AS \"SPID\",\t\t\t\t\t\t\t\t\t\t-- system process id (connection to sql)\r\n\t\t\t Deadlock.Process.value('@sbid', 'int') AS \"SBID\",\t\t\t\t\t\t\t\t\t\t-- system batch id / request_id (a query that a SPID is running)\r\n\t\t\t Deadlock.Process.value('@ecid', 'int') AS \"ECID\",\t\t\t\t\t\t\t\t\t\t-- execution context ID (a worker thread running part of a query)\r\n\t\t\t Deadlock.Process.value('@isolationlevel', 'varchar(200)') AS \"IsolationLevel\",\r\n\t\t\t Deadlock.Process.value('@waitresource', 'varchar(200)') AS \"WaitResource\",\r\n\t\t\t Deadlock.Process.value('@logused', 'int') AS \"LogUsed\",\r\n\t\t\t Deadlock.Process.value('@clientapp', 'varchar(100)') AS \"ClientApp\",\r\n\t\t\t Deadlock.Process.value('@hostname', 'varchar(20)') AS \"HostName\",\r\n\t\t\t Deadlock.Process.value('@loginname', 'varchar(20)') AS \"LoginName\",\r\n\t\t\t Deadlock.Process.value('@lasttranstarted', 'datetime') AS \"TransactionTime\",\r\n\t\t\t Deadlock.Process.value('@lastbatchstarted', 'datetime') AS \"BatchStarted\",\r\n\t\t\t Deadlock.Process.value('@lastbatchcompleted', 'datetime') AS \"BatchCompleted\",\r\n\t\t\t Input.Buffer.query('.') AS \"InputBuffer\",\r\n\t\t\t CTE.DeadlockGraph,\r\n\t\t\t ES.ExecutionStack,\r\n\t\t\t ExecStack.Stack.value('@sqlhandle', 'varchar(64)') AS \"SQLHandle\",\r\n\t\t\t NULLIF(ExecStack.Stack.value('.', 'varchar(max)'), '') AS \"QueryStatement\",\t\t\t--[QueryStatement] = Execution.Frame.value('.', 'varchar(max)'),\r\n\t\t\t SUM(1) OVER (PARTITION BY CTE.DeadlockID) AS \"ProcessQty\",\r\n\t\t\t Deadlock.Process.value('@trancount', 'int') AS \"TranCount\"\r\n\t FROM _DeadLocks AS CTE\r\n\t CROSS APPLY CTE.DeadlockGraph.nodes('//deadlock/process-list/process') AS Deadlock(Process)\r\n\t CROSS APPLY (SELECT Deadlock.Process.value('@id', 'varchar(50)')) AS Process(ID)\r\n\t LEFT JOIN _Victims AS V ON Process.ID = V.ID\r\n\t CROSS APPLY Deadlock.Process.nodes('inputbuf') AS Input(Buffer)\r\n\t CROSS APPLY Deadlock.Process.nodes('executionStack') AS Execution(Frame)\r\n\t -- Get the Data from the Execution Stack Node as XML\r\n\t CROSS APPLY (\r\n\t\t\t\t\t SELECT (\r\n\t\t\t\t\t\t\t\t SELECT ROW_NUMBER() OVER (PARTITION BY CTE.DeadlockID,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t Deadlock.Process.value('@id', 'varchar(50)'),\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t Execution.Stack.value('@procname', 'sysname'),\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t Execution.Stack.value('@code', 'varchar(MAX)')\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tORDER BY (SELECT 1)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t ) AS \"ProcNumber\",\r\n\t\t\t\t\t\t\t\t\t\t Execution.Stack.value('@procname', 'sysname') AS \"ProcName\",\r\n\t\t\t\t\t\t\t\t\t\t Execution.Stack.value('@line', 'int') AS \"Line\",\r\n\t\t\t\t\t\t\t\t\t\t Execution.Stack.value('@sqlhandle', 'varchar(64)') AS \"SQLHandle\",\r\n\t\t\t\t\t\t\t\t\t\t LTRIM(RTRIM(Execution.Stack.value('.', 'varchar(MAX)'))) AS \"Code\"\r\n\t\t\t\t\t\t\t\t FROM Execution.Frame.nodes('frame') AS Execution(Stack)\r\n\t\t\t\t\t\t\t\t ORDER BY ProcNumber\r\n\t\t\t\t\t\t\t\t FOR XML PATH('frame'), ROOT('executionStack'), TYPE\r\n\t\t\t\t\t\t\t ) AS \"ExecutionStack\"\r\n\t\t\t\t ) AS ES\r\n\t CROSS APPLY Execution.Frame.nodes('frame') AS ExecStack(Stack)\r\n )\r\n-- Get the Columns in the Desired Order\r\nSELECT P.DeadlockID,\r\n\t P.Victim,\r\n\t P.ProcessQty,\r\n\t DENSE_RANK() OVER (PARTITION BY P.DeadlockID ORDER BY P.ProcessID) AS \"ProcessNum\",\r\n\t P.LockMode,\r\n\t NULLIF(L.ObjectName, '') AS \"LockedObject\",\r\n\t L.Database_id,\r\n\t L.AssociatedObjectId,\r\n\t P.ProcessID AS \"LockProcess\",\r\n\t P.KPID,\r\n\t P.SPID,\r\n\t P.SBID,\r\n\t P.ECID,\r\n\t P.TranCount,\r\n\t L.LockEvent,\r\n\t L.LockMode AS \"LockedMode\",\r\n\t L.WaitProcessId,\r\n\t L.WaitMode,\r\n\t P.WaitResource,\r\n\t L.WaitType,\r\n\t P.IsolationLevel,\r\n\t P.LogUsed,\r\n\t P.ClientApp,\r\n\t P.HostName,\r\n\t P.LoginName,\r\n\t P.TransactionTime,\r\n\t P.BatchStarted,\r\n\t P.BatchCompleted,\r\n\t P.QueryStatement,\r\n\t P.SQLHandle,\r\n\t P.InputBuffer,\r\n\t P.DeadlockGraph,\r\n\t P.ExecutionStack\r\nFROM _Process AS P\r\nLEFT JOIN _Locks AS L ON P.DeadlockID = L.DeadlockID AND P.ProcessID = L.LockProcessId\r\nORDER BY P.DeadlockID, P.Victim DESC, P.ProcessID;",
"placeholders": [
{
"name": "DeadLockFilePath",
"defaultValue": "C:\\SQL\\Deadlocks"
},
{
"name": "DeadLockFileName",
"defaultValue": "DeadLock001"
}
]
}
{
"id": "6b70ce8d-ce56-430e-abf9-ba34e508825f",
"prefix": "TDC_Admin_GetDriveSpaceUsedByDatabaseFiles",
"description": "To Check the SQL Database Files w.r.to Disk Utilization",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9796852Z",
"permissions": [],
"body": "USE [master];\r\nGO\r\n--\r\nDECLARE @DatabaseFiles TABLE\r\n(\r\n DBid INT,\r\n DBname sysname,\r\n LogicalFileName sysname,\r\n FileType NVARCHAR(128),\r\n FileGroupName NVARCHAR(128),\r\n PhysicalFileName NVARCHAR(2048),\r\n FileSize FLOAT,\r\n SpaceUsed FLOAT,\r\n SpaceFree FLOAT,\r\n MaxSize INT,\r\n Growth INT,\r\n is_percent_growth BIT\r\n);\r\n\r\nINSERT INTO @DatabaseFiles\r\nEXEC sys.sp_MSforeachdb 'use [?]; \r\nSELECT DB_ID() AS \"DBid\",\r\n\t DB_NAME() AS \"DBname\",\r\n\t DF.name AS \"LogicalFileName\",\r\n\t DF.type_desc AS \"FileType\",\r\n\t FG.name AS \"FileGroupName\",\r\n\t DF.physical_name AS \"PhysicalFileName\",\r\n\t DF.size AS \"FileSize\",\r\n\t CAST(FILEPROPERTY(DF.name, ''SpaceUsed'') AS INT) AS \"SpaceUsed\",\r\n\t DF.size - CAST(FILEPROPERTY(DF.name, ''SpaceUsed'') AS INT) AS \"SpaceFree\",\r\n\t DF.max_size AS \"MaxSize\",\r\n\t DF.growth AS \"Growth\",\r\n\t DF.is_percent_growth AS \"is_percent_growth\"\r\nFROM sys.database_files AS DF\r\nLEFT OUTER JOIN sys.filegroups AS FG ON FG.data_space_id = DF.data_space_id\r\nWHERE DF.type IN ( 0, 1 );';\r\n--\r\n;WITH _CTE_DriveSpace\r\nAS (\r\n SELECT DISTINCT\r\n volume_mount_point AS \"Drive\",\r\n file_system_type AS \"FileSystemType\",\r\n logical_volume_name AS \"LogicalDriveName\",\r\n CASE\r\n WHEN CONVERT(DECIMAL(18, 2), CAST(total_bytes AS FLOAT) / 1024 /*KB*/ / 1024 /*MB*/ / 1024 /*GB*/) > 1000 /*GB*/\r\n THEN CAST(CAST(ROUND(CAST(total_bytes AS FLOAT) / 1024 /*KB*/ / 1024 /*MB*/ / 1024 /*GB*/ / 1024 /*TB*/, 2, 1) AS DECIMAL(18, 2)) AS VARCHAR(32)) + ' TB'\r\n ELSE CAST(CAST(ROUND(CAST(total_bytes AS FLOAT) / 1024 /*KB*/ / 1024 /*MB*/ / 1024 /*GB*/, 2, 1) AS DECIMAL(18, 2)) AS VARCHAR(32)) + ' GB'\r\n END AS \"TotalSize\",\r\n CASE\r\n WHEN CONVERT(DECIMAL(18, 2), CAST(available_bytes AS FLOAT) / 1024 /*KB*/ / 1024 /*MB*/ / 1024 /*GB*/) > 1000 /*GB*/\r\n THEN CAST(CAST(ROUND(CAST(available_bytes AS FLOAT) / 1024 /*KB*/ / 1024 /*MB*/ / 1024 /*GB*/ / 1024 /*TB*/, 2, 1) AS DECIMAL(18, 2)) AS VARCHAR(32)) + ' TB'\r\n ELSE CAST(CAST(ROUND(CAST(available_bytes AS FLOAT) / 1024 /*KB*/ / 1024 /*MB*/ / 1024 /*GB*/, 2, 1) AS DECIMAL(18, 2)) AS VARCHAR(32)) + ' GB'\r\n END AS \"AvailableSize\",\r\n CAST(ROUND((CAST(available_bytes AS FLOAT) / CAST(total_bytes AS FLOAT) * 100), 2, 1) AS DECIMAL(18, 2)) AS \"FreeSpace%\"\r\n FROM sys.master_files\r\n CROSS APPLY sys.dm_os_volume_stats(database_id, file_id)\r\n )\r\nSELECT CDS.[Drive],\r\n CDS.[TotalSize] AS \"TotalDriveSize\",\r\n CDS.[AvailableSize] AS \"DriveFreeSpace\",\r\n CDS.[FreeSpace%],\r\n '|' AS \" \",\r\n DF.DBname AS \"DatabaseName\",\r\n DF.LogicalFileName AS \"LogicalFileName\",\r\n CASE DF.FileType \r\n WHEN 'LOG' THEN DF.FileType + ' | ' + DBs.log_reuse_wait_desc COLLATE DATABASE_DEFAULT \r\n\t\t ELSE df.FileType \r\n END AS \"FileType | LogWait\",\r\n DF.FileGroupName AS \"FileGroupName\",\r\n DF.PhysicalFileName AS \"PhysicalFileLocation\",\r\n DBs.recovery_model_desc AS \"RecoveryModel\",\r\n CAST(DF.FileSize * 8.0 /*KB*/ / 1024.0 /*MB*/ AS DECIMAL(10,2)) AS \"TotalSize(MB)\",\r\n CAST(DF.SpaceUsed * 8.0 /*KB*/ / 1024.0 /*MB*/ AS DECIMAL(10,2)) AS \"UsedSpace(MB)\",\r\n CAST(DF.SpaceFree * 8.0 /*KB*/ / 1024.0 /*MB*/ AS DECIMAL(10,2)) AS \"FreeSpace(MB)\",\r\n CASE DF.is_percent_growth\r\n WHEN 1 THEN CONVERT(NVARCHAR(15), DF.Growth) + N'%'\r\n ELSE CONVERT(NVARCHAR(15), (DF.Growth * 8 /*KB*/ / 1024 /*MB*/)) + N' MB'\r\n END AS \"FileGrowth\",\r\n CASE DF.MaxSize\r\n WHEN 0 THEN 'Limited'\r\n WHEN - 1 THEN 'UnLimited'\r\n WHEN 268435456 THEN 'UpTo 2 TB'\r\n ELSE 'Limited (' + CONVERT(VARCHAR(15), DF.MaxSize * 8 /*KB*/ / 1024 /*MB*/) + ' MB)'\r\n END AS \"RestrictedGrowth\"\r\nFROM _CTE_DriveSpace AS CDS\r\nINNER JOIN @DatabaseFiles AS DF ON RTRIM(CDS.[Drive]) = LEFT(DF.PhysicalFileName, 3)\r\nINNER JOIN sys.databases AS DBs ON DF.DBid = DBs.database_id\r\nWHERE 1=1 \r\n --AND DB_NAME(DF.DBid) IN ('master')\r\nORDER BY CDS.[Drive],\r\n DF.DBname ASC ;"
}
{
"id": "bc1acc4d-9540-4214-9b3f-3974eb3d0ca7",
"prefix": "TDC_Admin_GetGateWayCounts",
"description": "",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9796852Z",
"permissions": [],
"body": "/*\r\n\tAuthor: Tim Cartwright, Daniel Berber\r\n\tPurpose: To get the compile gateway counts out of sql server. Most likely if you are hitting gateway issues, \r\n\t\tyou are seeing RESOURCE_SEMAPHORE_QUERY_COMPILE wait stats. The gateways act as a sort of funnel. \r\n\t\tThe more compile memory a plan needs, the bigger the gateway required. If the number of queries being compiled\r\n\t\tfor that gate way exceed the available count then the following queries will get stuck waiting with the \r\n\t\tRESOURCE_SEMAPHORE_QUERY_COMPILE wait stat. \r\n\tIf you are using SQL Server 2016 or greater you can use: sys.dm_exec_query_optimizer_memory_gateways\r\n\thttps://docs.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-exec-query-optimizer-memory-gateways?view=sql-server-ver15\r\n*/\r\n\r\nIF OBJECT_ID('tempdb..#mem_status') IS NOT NULL BEGIN \r\n DROP TABLE #mem_status \r\nEND\r\n\r\ncreate table #mem_status (\r\n id INT NOT NULL IDENTITY,\r\n counter varchar(80) null,\r\n value bigint NULL\r\n)\r\ninsert into #mem_status (counter, value) exec ('dbcc memorystatus')\r\n\r\n-- have to find the first row as the output row count is not always static\r\nDECLARE @firstId INT = (\r\n\tSELECT ID FROM (\r\n\t\tSELECT row = ROW_NUMBER() OVER (ORDER BY id), ID from #mem_status \r\n\t\tWHERE counter = 'Configured Units' \r\n\t) t WHERE t.row = 4\r\n)\r\n\r\nSELECT * FROM (\r\n\t-- small gateway\r\n\tSELECT 'Small Gateway (default)' as dataset, \r\n\t\tcounter, \r\n\t\tvalue\r\n\tFROM #mem_status \r\n\tWHERE id >= @firstId AND id <= @firstId + 5\r\n\t\tUNION\r\n\t-- medium gateway\r\n\tSELECT 'Medium Gateway (default)' as dataset, \r\n\t\tcounter, \r\n\t\tvalue\r\n\tFROM #mem_status \r\n\tWHERE id >= (@firstId + 6) AND id <= (@firstId + 11)\r\n\t\tUNION\r\n\t-- large gateway\r\n\tSELECT 'Big Gateway (default)' as dataset, \r\n\t\tcounter, \r\n\t\tvalue\r\n\tFROM #mem_status \r\n\tWHERE id >= (@firstId + 12) AND id <= (@firstId + 17)\r\n) gw \r\n--WHERE gw.counter = 'Waiters' AND gw.value > 0\t"
}
{
"id": "d54a19da-f1be-45e1-a8f8-638c56782c01",
"prefix": "TDC_Admin_GetPartitionedTableInfo",
"description": "Get Partitioned Table Information",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9796852Z",
"permissions": [],
"body": "/* =========================================================================================================================================\r\n-- Server\t\t: Local Server\r\n-- Database\t\t: User Database\r\n-- Script\t\t: GetPartitionedTableInformation\r\n-- Description\t: To Get Partitioned Table Information\r\n-- Usage\t\t:\r\n-- History\t\t:\r\n-- Link\t\t\t: https://www.cathrinewilhelmsen.net/table-partitioning-in-sql-server/\r\n--\t\t\t\t: https://www.youtube.com/watch?v=ZVAZZqFSsgU\r\n========================================================================================================================================= */\r\nSELECT\r\n OBJECT_SCHEMA_NAME(PSTATS.object_id) AS SchemaName,\r\n OBJECT_NAME(PSTATS.object_id) AS TableName,\r\n PS.name AS PartitionSchemeName,\r\n DS.name AS PartitionFilegroupName,\r\n PF.name AS PartitionFunctionName,\r\n CASE PF.boundary_value_on_right WHEN 0 THEN 'Range Left' ELSE 'Range Right' END AS PartitionFunctionRange,\r\n CASE PF.boundary_value_on_right WHEN 0 THEN 'Upper Boundary' ELSE 'Lower Boundary' END AS PartitionBoundary,\r\n PRV.value AS PartitionBoundaryValue,\r\n C.name AS PartitionKey,\r\n CASE\r\n WHEN PF.boundary_value_on_right = 0 \r\n THEN C.name + ' > ' + CAST(ISNULL(LAG(PRV.value) OVER(PARTITION BY PSTATS.object_id ORDER BY PSTATS.object_id, PSTATS.partition_number), '(-)Infinity') AS VARCHAR(100)) + ' and ' + C.name + ' <= ' + CAST(ISNULL(PRV.value, '(+)Infinity') AS VARCHAR(100)) \r\n ELSE C.name + ' >= ' + CAST(ISNULL(PRV.value, '(-)Infinity') AS VARCHAR(100)) + ' and ' + C.name + ' < ' + CAST(ISNULL(LEAD(PRV.value) OVER(PARTITION BY PSTATS.object_id ORDER BY PSTATS.object_id, PSTATS.partition_number), '(+)Infinity') AS VARCHAR(100))\r\n END AS PartitionRange,\r\n PSTATS.partition_number AS PartitionNumber,\r\n PSTATS.row_count AS PartitionRowCount,\r\n P.data_compression_desc AS DataCompression\r\nFROM sys.dm_db_partition_stats AS PSTATS\r\nINNER JOIN sys.partitions AS P ON PSTATS.partition_id = P.partition_id\r\nINNER JOIN sys.destination_data_spaces AS DDS ON PSTATS.partition_number = DDS.destination_id\r\nINNER JOIN sys.data_spaces AS DS ON DDS.data_space_id = DS.data_space_id\r\nINNER JOIN sys.partition_schemes AS PS ON DDS.partition_scheme_id = PS.data_space_id\r\nINNER JOIN sys.partition_functions AS PF ON PS.function_id = PF.function_id\r\nINNER JOIN sys.indexes AS I ON PSTATS.object_id = I.object_id AND PSTATS.index_id = I.index_id AND DDS.partition_scheme_id = I.data_space_id AND I.type <= 1 /* Heap or Clustered Index */\r\nINNER JOIN sys.index_columns AS IC ON I.index_id = IC.index_id AND I.object_id = IC.object_id AND IC.partition_ordinal > 0\r\nINNER JOIN sys.columns AS C ON PSTATS.object_id = C.object_id AND IC.column_id = C.column_id\r\nLEFT JOIN sys.partition_range_values AS PRV ON PF.function_id = PRV.function_id AND PSTATS.partition_number = (CASE PF.boundary_value_on_right WHEN 0 THEN PRV.boundary_id ELSE (PRV.boundary_id+1) END)\r\n--WHERE PSTATS.object_id = OBJECT_ID('[schema_name].[table_name]')\r\nORDER BY TableName, PartitionNumber;"
}
{
"id": "06c61315-3060-4d71-b426-fa5461e25512",
"prefix": "TDC_Admin_GetRowCountOnly",
"description": "Get Row Count for Each Table",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9796852Z",
"permissions": [],
"body": "SELECT OBJECT_SCHEMA_NAME(DDPS.object_id) AS \"SchemaName\",\r\n\t OBJECT_NAME(DDPS.object_id) AS \"TableName\",\r\n\t SUM(IIF((DDPS.index_id < 2), DDPS.row_count, 0)) AS \"Rows\"\r\nFROM sys.dm_db_partition_stats AS DDPS\r\nWHERE OBJECT_SCHEMA_NAME(DDPS.object_id) <> 'sys'\r\n\t--AND OBJECT_SCHEMA_NAME(DDPS.object_id) IN ( 'dbo' )\r\n\t--AND OBJECT_NAME(DDPS.object_id) IN ( 'TableName' )\r\nGROUP BY DDPS.object_id\r\n--HAVING SUM(IIF((DDPS.index_id < 2), DDPS.row_count, 0)) > 0\r\nORDER BY SchemaName, TableName ASC;"
}
{
"id": "847ccfd1-08ad-4558-9686-01ce5cd12927",
"prefix": "TDC_Admin_GetServerLevelSecurity",
"description": "",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9806853Z",
"permissions": [],
"body": "/*\r\nTIM C: I wrote this so I can dump server level security and easily glance over it, as well as: \r\n\t- can be used to compare security from server to server\r\n\t- automatically exported every so often so changes can be monitored over time\r\n\t- used to clean up dead accounts\r\n\t- password hash could be added to the sql users for AG primary->secondary comparison, \r\n\t\t- TO ENABLE PWD HASH EXPORT CHANGE @output_pwds BELOW\r\n*/\r\n\r\nBEGIN --principals table\r\n IF OBJECT_ID('tempdb..#principals') IS NOT NULL\r\n BEGIN\r\n DROP TABLE #principals;\r\n END;\r\n\r\n CREATE TABLE #principals\r\n (\r\n account_name sysname,\r\n type VARCHAR(50) NULL,\r\n privilege VARCHAR(50) NULL,\r\n mapped_login_name sysname,\r\n permission_path sysname NULL\r\n );\r\nEND;\r\nGO\r\n\r\nBEGIN --groups table\r\n IF OBJECT_ID('tempdb..#groups') IS NOT NULL\r\n BEGIN\r\n DROP TABLE #groups;\r\n END;\r\n\r\n CREATE TABLE #groups\r\n (\r\n group_id INT IDENTITY NOT NULL,\r\n group_name sysname,\r\n error VARCHAR(1028),\r\n PRIMARY KEY CLUSTERED (group_name)\r\n );\r\nEND;\r\nGO\r\n\r\nBEGIN --users table\r\n IF OBJECT_ID('tempdb..#users') IS NOT NULL\r\n BEGIN\r\n DROP TABLE #users;\r\n END;\r\n\r\n CREATE TABLE #users\r\n (\r\n user_id INT IDENTITY NOT NULL,\r\n user_name sysname,\r\n group_id INT NOT NULL,\r\n error VARCHAR(1028),\r\n type CHAR(1)\r\n DEFAULT ('U') NOT NULL,\r\n PRIMARY KEY CLUSTERED (\r\n user_name,\r\n group_id\r\n )\r\n );\r\nEND;\r\nGO\r\n\r\n-- insert a fake group to account for server level accounts\r\nSET IDENTITY_INSERT #groups ON;\r\nINSERT INTO #groups\r\n(\r\n group_id,\r\n group_name\r\n)\r\nVALUES\r\n(-1, 'SERVER LEVEL ACCOUNT');\r\nSET IDENTITY_INSERT #groups OFF;\r\n\r\nIF OBJECT_ID(N'tempdb..#addLogins') IS NOT NULL\r\nBEGIN\r\n DROP PROCEDURE #addLogins;\r\nEND;\r\nGO\r\n\r\nCREATE PROCEDURE #addLogins\r\n(\r\n @acctname sysname,\r\n @type CHAR(1)\r\n)\r\nAS\r\nBEGIN\r\n BEGIN TRY\r\n SET NOCOUNT ON;\r\n TRUNCATE TABLE #principals;\r\n IF @type IN ( 'G', 'U' )\r\n BEGIN\r\n DECLARE @options VARCHAR(10) = CASE\r\n WHEN @type = 'G' THEN\r\n 'members'\r\n WHEN @type = 'U' THEN\r\n 'all'\r\n END;\r\n\r\n INSERT INTO #principals\r\n (\r\n account_name,\r\n type,\r\n privilege,\r\n mapped_login_name,\r\n permission_path\r\n )\r\n EXEC sys.xp_logininfo @acctname = @acctname, @option = @options;\r\n END;\r\n\r\n IF @type = 'G'\r\n BEGIN\r\n INSERT INTO #groups\r\n (\r\n group_name\r\n )\r\n SELECT TOP (1)\r\n permission_path\r\n FROM #principals p\r\n ORDER BY p.account_name;\r\n\r\n DECLARE @gid INT = SCOPE_IDENTITY();\r\n\r\n INSERT INTO #users\r\n (\r\n user_name,\r\n group_id\r\n )\r\n SELECT account_name,\r\n @gid\r\n FROM #principals;\r\n\r\n END;\r\n ELSE IF @type IN ( 'S', 'U' )\r\n BEGIN\r\n MERGE #users AS [target]\r\n USING\r\n (\r\n VALUES\r\n (@acctname, @type)\r\n ) AS [source] ([user_name], [type])\r\n ON (\r\n target.[user_name] = source.[user_name]\r\n AND target.group_id = -1\r\n )\r\n WHEN MATCHED AND (source.[user_name] <> target.[user_name]) THEN\r\n UPDATE SET [user_name] = source.[user_name],\r\n [type] = source.[type]\r\n WHEN NOT MATCHED BY TARGET THEN\r\n INSERT\r\n (\r\n group_id,\r\n [user_name],\r\n [type]\r\n )\r\n VALUES\r\n (-1, source.[user_name], source.[type]);\r\n END;\r\n END TRY\r\n BEGIN CATCH\r\n DECLARE @errorMessage NVARCHAR(4000) = ERROR_MESSAGE();\r\n IF @type = 'G'\r\n BEGIN\r\n INSERT INTO #groups\r\n (\r\n group_name,\r\n error\r\n )\r\n VALUES\r\n (@acctname, @errorMessage);\r\n END;\r\n ELSE IF @type = 'U'\r\n BEGIN\r\n INSERT INTO #users\r\n (\r\n group_id,\r\n user_name,\r\n error,\r\n [type]\r\n )\r\n VALUES\r\n (-1, @acctname, @errorMessage, @type);\r\n END;\r\n END CATCH;\r\nEND;\r\nGO\r\n-- generate the sql to call the #addLogins proc to populate the #users, and #groups tables\r\nDECLARE @sql NVARCHAR(MAX) = N'';\r\nDECLARE @output_pwds BIT = 0;\r\n\r\n\r\nSELECT @sql += N'EXEC #addLogins @acctname = ''' + sp.name + N''', @type = '''\r\n + sp.type COLLATE SQL_Latin1_General_CP1_CI_AS + N''';' + CHAR(13) + CHAR(10)\r\nFROM master.sys.server_principals sp\r\nWHERE sp.type IN ( 'G', 'U', 'S' )\r\n AND sp.name NOT LIKE 'NT SERVICE%'\r\n AND sp.name NOT LIKE 'NT AUTHORITY%'\r\nORDER BY sp.type,\r\n sp.name;\r\n\r\n--PRINT @sql\r\nEXEC (@sql);\r\n\r\n--out put the data as xml, include role memberships for groups and user server accounts\r\nSELECT [@name] = [g].group_name,\r\n [@error] = g.error,\r\n (\r\n SELECT [@name] = sp.name\r\n FROM sys.server_principals sp\r\n WHERE sp.type = 'R'\r\n AND sp.name <> 'public'\r\n AND IS_SRVROLEMEMBER(sp.name, g.group_name) = 1\r\n FOR XML PATH('ServerRole'), ELEMENTS, TYPE\r\n ) AS [ServerRoles],\r\n (\r\n SELECT [@name] = sper.permission_name\r\n FROM sys.server_permissions sper\r\n INNER JOIN sys.server_principals sp\r\n ON sp.principal_id = sper.grantee_principal_id\r\n WHERE sper.type <> 'COSQ'\r\n AND sp.name = g.group_name\r\n FOR XML PATH('ServerPermission'), ELEMENTS, TYPE\r\n ) AS [ServerPermissions],\r\n (\r\n SELECT [@name] = u.user_name,\r\n [@error] = u.error,\r\n [@type] = CASE\r\n WHEN g.group_id = -1 THEN\r\n CASE\r\n WHEN u.type = 'S' THEN 'SQL'\r\n WHEN u.type = 'U' THEN 'WINDOWS'\r\n ELSE NULL\r\n END\r\n ELSE NULL\r\n END,\r\n [@hashed_pwd] = CASE\r\n\t\t\t\t\t\tWHEN @output_pwds = 1\r\n\t\t\t\t\t\t\tAND g.group_id = -1\r\n\t\t\t\t\t\t\tAND u.type = 'S' THEN\r\n\t\t\t\t\t\t\tCONVERT(NVARCHAR(4000), LOGINPROPERTY(u.user_name, 'PASSWORDHASH'), 1)\r\n\t\t\t\t\t\tELSE NULL\r\n\t\t\t\t\tEND,\r\n (\r\n SELECT [@name] = r.name\r\n FROM sys.server_role_members rm\r\n INNER JOIN sys.server_principals r\r\n ON r.principal_id = rm.role_principal_id\r\n AND r.type = 'R'\r\n INNER JOIN sys.server_principals m\r\n ON m.principal_id = rm.member_principal_id\r\n WHERE m.name = u.user_name\r\n AND r.name <> 'public'\r\n FOR XML PATH('ServerRole'), ELEMENTS, TYPE\r\n ) AS [ServerRoles],\r\n (\r\n SELECT [@name] = sper.permission_name\r\n FROM sys.server_permissions sper\r\n INNER JOIN sys.server_principals sp\r\n ON sp.principal_id = sper.grantee_principal_id\r\n WHERE sper.type <> 'COSQ'\r\n AND g.group_id = -1\r\n AND sp.name = u.user_name\r\n FOR XML PATH('ServerPermission'), ELEMENTS, TYPE\r\n ) AS [ServerPermissions]\r\n FROM #users u\r\n WHERE u.group_id = g.group_id\r\n FOR XML PATH('User'), ELEMENTS, TYPE\r\n ) AS [Users]\r\nFROM #groups [g]\r\nORDER BY [g].group_name\r\nFOR XML PATH('Group'), ROOT('Groups');\r\n"
}
{
"id": "afcc59ed-add2-4d03-9ef6-80449af1f543",
"prefix": "TDC_Admin_GetSessionLocks",
"description": "Get Session Locks",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9806853Z",
"permissions": [],
"body": "-- only create the temp table #partitions ONCE. DROP if needed to recreate\r\n-- DROP TABLE #partitions\r\n\r\nIF OBJECT_ID('tempdb..#partitions') IS NULL BEGIN \r\n -- table to hold all of the partition information \r\n CREATE TABLE #partitions (\r\n database_id int NOT NULL,\r\n database_name sysname NOT NULL,\r\n partition_id bigint NOT NULL,\r\n object_id INT NOT NULL,\r\n index_id INT NOT NULL,\r\n hobt_id bigint NOT NULL,\r\n index_name sysname NULL\r\n )\r\n\r\n -- build a query to get all the partitions from all of the accessible dbs that are not readonly\r\n DECLARE @sql VARCHAR(MAX) = (\r\n SELECT REPLACE(REPLACE(STUFF((\r\n SELECT CONCAT('UNION ALL ##CRLF##SELECT [database_id] = ', d.database_id, \r\n ', [database_name] = ''', d.name, \r\n ''', p.partition_id, p.object_id, p.index_id, p.hobt_id, i.name COLLATE SQL_Latin1_General_CP1_CI_AS FROM [', d.name, '].sys.partitions p ', \r\n 'INNER JOIN [', d.name, '].sys.indexes i ON i.object_id = p.object_id AND i.index_id = p.index_id WHERE p.object_id >= 100', ' ') \r\n FROM sys.databases d\r\n WHERE d.is_read_only = 0\r\n AND HAS_DBACCESS(d.name) = 1\r\n FOR XML PATH('')\r\n ), 1, 18, ''), '##CRLF##', CONCAT(CHAR(13), CHAR(10))), '&gt;', '>')\r\n )\r\n\r\n --SELECT @sql\r\n -- insert all of the partition information into the table \r\n INSERT INTO #partitions (\r\n database_id,\r\n database_name,\r\n partition_id,\r\n object_id,\r\n index_id,\r\n hobt_id,\r\n index_name\r\n )\r\n EXEC (@sql)\r\n\r\n -- SELECT * FROM #partitions\r\nEND\r\n\r\nSELECT des.session_id,\r\n des.host_name, \r\n des.login_name, \r\n des.program_name,\r\n --dtl.resource_database_id,\r\n --dtl.resource_associated_entity_id,\r\n DB_NAME(dtl.resource_database_id) AS [db_name],\r\n fn.[object_name],\r\n p.index_name,\r\n dtl.resource_type,\r\n dtl.request_mode,\r\n dtl.request_status,\r\n [count] = COUNT(*)\r\nFROM sys.dm_tran_locks dtl WITH(NOLOCK)\r\nINNER JOIN sys.dm_exec_sessions des WITH(NOLOCK)\r\n ON des.session_id = dtl.request_session_id\r\nLEFT JOIN #partitions p \r\n ON p.database_id = dtl.resource_database_id\r\n AND p.hobt_id = dtl.resource_associated_entity_id\r\nCROSS APPLY (\r\n\tSELECT CASE \r\n WHEN DTL.resource_type = 'OBJECT' THEN \r\n OBJECT_SCHEMA_NAME(DTL.resource_associated_entity_id, dtl.resource_database_id) + '.' + OBJECT_NAME(DTL.resource_associated_entity_id, DTL.[resource_database_id])\r\n WHEN DTL.resource_type IN ('KEY', 'PAGE', 'RID', 'HOBT') THEN \r\n OBJECT_SCHEMA_NAME(p.object_id, dtl.resource_database_id) + '.' + OBJECT_NAME(p.object_id, DTL.[resource_database_id])\r\n ELSE DTL.resource_type\r\n END AS [object_name]\r\n) fn\r\nWHERE dtl.resource_associated_entity_id > 0\r\n AND des.session_id <> @@SPID\r\n AND DB_NAME(dtl.resource_database_id) <> 'tempdb'\r\n\t-- AND fn.[object_name] = 'dbo.Users'\r\nGROUP BY des.session_id,\r\n des.host_name, \r\n des.login_name, \r\n des.program_name,\r\n\tfn.object_name,\r\n dtl.resource_database_id,\r\n dtl.resource_type,\r\n dtl.request_mode,\r\n dtl.request_status,\r\n dtl.resource_associated_entity_id,\r\n p.object_id,\r\n p.index_name\r\nORDER BY [db_name],\r\n [object_name], \r\n [count] desc\r\n\r\n\r\n/*\r\n-- QUERY TO INSPECT ALLOCATION UNITS IF NEEDED:\r\nSELECT p.partition_id,\r\n p.object_id,\r\n OBJECT_NAME(p.object_id) AS object_name,\r\n i.name AS index_name,\r\n i.type_desc AS index_type,\r\n p.partition_number,\r\n au.type_desc AS allocation_unit_type,\r\n au.total_pages,\r\n au.data_pages\r\nFROM sys.allocation_units AS au\r\nINNER JOIN sys.partitions AS p\r\n ON p.partition_id = au.container_id\r\nINNER JOIN sys.indexes AS i\r\n ON p.object_id = i.object_id\r\n AND p.index_id = i.index_id\r\nWHERE (i.object_id > 100);\r\n*/"
}
{
"id": "b8b16502-3f2a-4712-b5d8-9e8e11c1d56e",
"prefix": "TDC_Admin_GetTablesDatailedHierarchy",
"description": "Get the Detailed Hierarchy of Tables using Existing Foreign Keys",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9806853Z",
"permissions": [],
"body": "/* =========================================================================================================================================\r\n-- Server\t\t: LOCALSERVER\r\n-- Database\t\t: USER Database\r\n-- Script\t\t: GetTablesDatailedHierarchy\r\n-- Description\t: Get Detailed Hierarchy of Tables using Existing Foreign Keys\r\n--\t\t\t\t**Note: Self Reference Foreign Keys should be Excluded or Dropped before Executing and Then ReCreated.\r\n========================================================================================================================================= */\r\nSET NOCOUNT ON;\r\nWITH _Dependencies -- Get Objects with FK Dependencies\r\nAS (\r\n\t SELECT FK.TABLE_SCHEMA AS \"OBJECTschema\", FK.TABLE_NAME AS \"OBJECTname\",\r\n\t\t\t PK.TABLE_SCHEMA AS \"DEPENDSschema\", PK.TABLE_NAME AS \"DEPENDSname\"\r\n\t FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS C\r\n\t INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS FK ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME\r\n\t INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS PK ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME\r\n ),\r\n_NoDependencies -- The First Level Objects are with No Dependencies\r\nAS (\r\n\t SELECT T.TABLE_SCHEMA AS \"OBJECTschema\", T.TABLE_NAME AS \"OBJECTname\"\r\n\t FROM INFORMATION_SCHEMA.TABLES AS T\r\n\t WHERE T.TABLE_TYPE = 'BASE TABLE' -- Just Tables Only\r\n\t\t\t AND NOT EXISTS (SELECT 1 FROM _Dependencies AS D WHERE D.OBJECTschema = T.TABLE_SCHEMA AND D.OBJECTname = T.TABLE_NAME)\r\n ),\r\n_Recursive -- Recursive CTE to Get Dependencies\r\nAS (\r\n\t SELECT ND.OBJECTschema AS \"SchemaName\", ND.OBJECTname AS \"TableName\", 0 AS \"LVL\", -- Level 0 Indicates Tables with No Dependencies\r\n\t CAST('' AS VARCHAR(MAX)) AS \"DependsON\"\r\n\t FROM _NoDependencies AS ND\r\n\t UNION ALL\r\n\t SELECT D.OBJECTschema AS \"SchemaName\", D.OBJECTname AS \"TableName\", R.LVL + 1 AS \"LVL\",\r\n\t CAST((CASE WHEN LVL > 0 THEN R.DependsON + ' => ' ELSE '' END) + ('['+D.DEPENDSschema+'].['+D.DEPENDSname+'] ('+CAST(R.LVL AS VARCHAR(2))+')') AS VARCHAR(MAX)) -- Visually Reflects Hierarchy\r\n\t FROM _Dependencies AS D\r\n\t INNER JOIN _Recursive AS R ON D.DEPENDSschema = R.SchemaName AND D.DEPENDSname = R.TableName\r\n )\r\nSELECT R.SchemaName, R.TableName, R.LVL,\r\nCASE WHEN R.LVL > 0 THEN R.DependsON + ' => ' + '['+R.SchemaName+'].['+R.TableName+'] ('+CAST(R.LVL AS VARCHAR(2))+')' ELSE R.DependsON END AS \"DependsOnHierarchy\"\r\nFROM _Recursive AS R\r\nORDER BY R.LVL ASC, R.SchemaName ASC, R.TableName ASC, R.DependsON ASC;"
}
{
"id": "7bde5d99-8699-4255-bfd0-55ae6ddb865f",
"prefix": "TDC_Admin_GetTablesHierarchyLevel",
"description": "Get Hierarchy Level of Tables using Existing Foreign Keys",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9816855Z",
"permissions": [],
"body": "/* =========================================================================================================================================\r\n-- Server\t\t: LOCALSERVER\r\n-- Database\t\t: USER Database\r\n-- Script\t\t: GetTablesHierarchyLevel\r\n-- Description\t: Get Hierarchy Level of Tables using Existing Foreign Keys\r\n--\t\t\t\t**Note: Self Reference Foreign Keys should be Excluded or Dropped before Executing and Then ReCreated.\r\n========================================================================================================================================= */\r\nSET NOCOUNT ON;\r\nWITH _Dependencies -- Get Objects with FK Dependencies\r\nAS (\r\n\t SELECT FK.TABLE_SCHEMA AS \"OBJECTschema\", FK.TABLE_NAME AS \"OBJECTname\",\r\n\t\t\t PK.TABLE_SCHEMA AS \"DEPENDSschema\", PK.TABLE_NAME AS \"DEPENDSname\"\r\n\t FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS C\r\n\t INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS FK ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME\r\n\t INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS PK ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME\r\n ),\r\n_NoDependencies -- The First Level Objects are with No Dependencies\r\nAS (\r\n\t SELECT T.TABLE_SCHEMA AS \"OBJECTschema\", T.TABLE_NAME AS \"OBJECTname\"\r\n\t FROM INFORMATION_SCHEMA.TABLES AS T\r\n\t WHERE T.TABLE_TYPE = 'BASE TABLE' -- Just Tables Only\r\n\t\t\t AND NOT EXISTS (SELECT 1 FROM _Dependencies AS D WHERE D.OBJECTschema = T.TABLE_SCHEMA AND D.OBJECTname = T.TABLE_NAME)\r\n ),\r\n_Recursive -- Recursive CTE to Get Dependencies\r\nAS (\r\n\t SELECT ND.OBJECTschema AS \"SchemaName\", ND.OBJECTname AS \"TableName\", 0 AS \"LVL\" -- Level 0 Indicates Tables with No Dependencies\r\n\t FROM _NoDependencies AS ND\r\n\t UNION ALL\r\n\t SELECT D.OBJECTschema AS \"SchemaName\", D.OBJECTname AS \"TableName\", R.LVL + 1 AS \"LVL\"\r\n\t FROM _Dependencies AS D\r\n\t INNER JOIN _Recursive AS R ON D.DEPENDSschema = R.SchemaName AND D.DEPENDSname = R.TableName\r\n )\r\nSELECT R.SchemaName, R.TableName, MAX(R.LVL) AS \"LVL\"\r\nFROM _Recursive AS R\r\nGROUP BY R.SchemaName, R.TableName\r\nORDER BY LVL ASC, R.SchemaName ASC, R.TableName ASC;"
}
{
"id": "171aa3cd-f38e-4206-a75e-d59a877db3f1",
"prefix": "TDC_Admin_GetTransactionInformation",
"description": "",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9816855Z",
"permissions": [],
"body": "/* \r\n -- TIM C \r\n Purpose: To show any runnning transactions, and how much transaction activity is being generated. Will also show\r\n if the spid is blocking any other spids and what spids are being blocked. Can be helpful in determining the \r\n rollback impact of killing a SPID. \r\n \r\n NOTE: Does not show any queries that are NOT enlisted in transactions.\r\n Origin SQL sourced from these articles: \r\n -- https://www.red-gate.com/simple-talk/sql/database-administration/investigating-transactions-using-dynamic-management-objects/\r\n -- https://www.mssqltips.com/sqlservertip/1811/find-current-running-sql-statement-in-sql-server/\r\n \r\n Modifications:\r\n 1) Added the transaction_begin_time to show log start time even on queries that are not generating log\r\n 2) Added code to extract the actual executing text out of the stored procedure, if the command is a stored procedure or a batch\r\n 3) Added an outter apply to determine if the spid is currently blocking any other spids, Outputs:\r\n a) a delimited list of all the blocked spids recursively\r\n b) how many spids are blocked\r\n c) that the spid is involved in blocking\r\n Outputs:\r\n session_id - the session id\r\n login_name - the login name running the session\r\n database - the database name\r\n program_name - the program name from the connection\r\n is_blocking - 1 if this session is blocking other sessions\r\n blocked_session_ids - a comma delimited list of all the blocked sessions \r\n blocked_session_count - a count of all the blocked sessions \r\n transaction_begin_time - the time at which the transaction started\r\n duration_seconds - how many seconds the transaction has been running\r\n log_begin_time - the time of the first log entries for the transaction\r\n transaction_type - type of transaction\r\n transaction_type_desc - description for type of transaction\r\n transaction_state - the current state of the transaction\r\n transaction_state_desc - description for the current state of the transaction\r\n log_records - number of log records generated in the database for the transaction\r\n log_bytes_used - number of bytes used so far in the database log for the transaction\r\n log_bytes_reserved - number of bytes reserved for use in the database log for the transaction\r\n last_command_text - the entirety of the last command executed\r\n last_executing_statement - the statement of the last sql executed of a stored procedure or a batch\r\n last_command_plan - the query plan of the last executed command\r\n Useful deciding factors:\r\n 1) If the log_begin_time is null, then no log records have been written which will result in no rollback\r\n 2) The more log_records, and log_bytes_used the more rollback will be incurred\r\n 3) If the log_bytes_used is near 50% of the log_bytes_reserved then the transaction is near to finishing \r\n as the log manager reserves 2x the log space needed per transaction.\r\n NOTE: This may be misleading as database_transaction_log_bytes_reserved may not mean what MSDN says it means. https://www.sqlskills.com/blogs/paul/script-open-transactions-with-text-and-plans/\r\n \r\n*/ \r\n\r\n;WITH Blocking AS (\r\n SELECT der.session_id,\r\n der.blocking_session_id,\r\n block_chain = ROW_NUMBER() OVER (ORDER BY der.session_id),\r\n 1 AS block_chain_link\r\n FROM sys.dm_exec_requests der\r\n WHERE der.blocking_session_id = 0\r\n AND EXISTS (\r\n SELECT 1 \r\n FROM sys.dm_exec_requests der1\r\n WHERE der1.blocking_session_id = der.session_id\r\n )\r\n UNION ALL\r\n SELECT der.session_id,\r\n der.blocking_session_id,\r\n d.block_chain,\r\n d.block_chain_link + 1\r\n FROM sys.dm_exec_requests der\r\n INNER JOIN Blocking d\r\n ON der.blocking_session_id = d.session_id\r\n WHERE der.blocking_session_id > 0\r\n)\r\n\r\nSELECT DTDT.transaction_id,\r\n DTST.[session_id],\r\n DES.[login_name] AS [login_name],\r\n DB_NAME(DTDT.database_id) AS [database],\r\n DES.program_name,\r\n fn2.[is_blocking], \r\n fn.blocked_session_ids,\r\n fn2.[blocked_session_count],\r\n DTAT.transaction_begin_time AS [transaction_begin_time],\r\n fn2.[duration_seconds], \r\n DTDT.[database_transaction_begin_time] AS [log_begin_time],\r\n DTAT.transaction_type,\r\n CASE DTAT.transaction_type\r\n WHEN 1 THEN 'Read/write'\r\n WHEN 2 THEN 'Read-only'\r\n WHEN 3 THEN 'System'\r\n WHEN 4 THEN 'Distributed'\r\n ELSE CONCAT('UNKNOWN: ', DTAT.transaction_type)\r\n END AS [transaction_type_desc],\r\n DTAT.transaction_state,\r\n CASE DTAT.transaction_state\r\n WHEN 0 THEN 'Not fully initialized'\r\n WHEN 1 THEN 'Initialized, not started'\r\n WHEN 2 THEN 'Active'\r\n WHEN 3 THEN 'Ended'\r\n WHEN 4 THEN 'Commit initiated'\r\n WHEN 5 THEN 'Prepared, awaiting resolution'\r\n WHEN 6 THEN 'Committed'\r\n WHEN 7 THEN 'Rolling back'\r\n WHEN 8 THEN 'Rolled back'\r\n ELSE CONCAT('UNKNOWN: ', DTAT.transaction_state)\r\n END AS [transaction_state_desc],\r\n DTDT.[database_transaction_log_record_count] AS [log_records],\r\n DTDT.[database_transaction_log_bytes_used] AS [log_bytes_used],\r\n DTDT.[database_transaction_log_bytes_reserved] AS [log_bytes_reserved],\r\n fn2.log_bytes_percent_used,\r\n DEST.[text] AS [last_command_text],\r\n CASE \r\n WHEN DER.[statement_start_offset] > 0 THEN \r\n /* The start of the active command is not at the beginning of the full command text */\r\n CASE DER.[statement_end_offset] \r\n WHEN -1 THEN \r\n /* The end of the full command is also the end of the active statement */\r\n SUBSTRING(DEST.TEXT, (DER.[statement_start_offset]/2) + 1, 2147483647) \r\n ELSE \r\n /* The end of the active statement is not at the end of the full command */\r\n SUBSTRING(DEST.TEXT, (DER.[statement_start_offset]/2) + 1, (DER.[statement_end_offset] - DER.[statement_start_offset])/2) \r\n END \r\n ELSE \r\n /* 1st part of full command is running */\r\n CASE DER.[statement_end_offset] \r\n WHEN -1 THEN \r\n /* The end of the full command is also the end of the active statement */\r\n RTRIM(LTRIM(DEST.[text])) \r\n ELSE \r\n /* The end of the active statement is not at the end of the full command */\r\n LEFT(DEST.TEXT, (DER.[statement_end_offset]/2) + 1) \r\n END \r\n END AS [last_executing_statement],\r\n DEQP.[query_plan] AS [last_command_plan] \r\nFROM sys.dm_tran_database_transactions DTDT\r\n INNER JOIN sys.dm_tran_session_transactions DTST\r\n ON DTST.[transaction_id] = DTDT.[transaction_id]\r\n INNER JOIN sys.[dm_tran_active_transactions] DTAT\r\n ON DTST.[transaction_id] = DTAT.[transaction_id]\r\n INNER JOIN sys.[dm_exec_sessions] DES\r\n ON DES.[session_id] = DTST.[session_id]\r\n INNER JOIN sys.dm_exec_connections DEC\r\n ON DEC.[session_id] = DTST.[session_id]\r\n LEFT JOIN sys.dm_exec_requests DER\r\n ON DER.[session_id] = DTST.[session_id]\r\n CROSS APPLY sys.dm_exec_sql_text(DEC.[most_recent_sql_handle]) AS DEST\r\n OUTER APPLY sys.dm_exec_query_plan(DER.[plan_handle]) AS DEQP\r\n OUTER APPLY (\r\n SELECT STUFF((\r\n SELECT CONCAT(',', der.session_id) \r\n FROM Blocking der \r\n WHERE der.blocking_session_id <> 0\r\n AND der.blocking_session_id = DTST.[session_id]\r\n AND der.session_id <> DTST.[session_id]\r\n FOR XML PATH('')\r\n ), 1, 1, '') AS [blocked_session_ids]\r\n ) fn\r\n OUTER APPLY (\r\n SELECT CASE WHEN LEN([fn].[blocked_session_ids]) > 0 THEN 1 ELSE 0 END AS [is_blocking], \r\n LEN(fn.blocked_session_ids) - LEN(REPLACE(fn.blocked_session_ids, ',', '')) + 1 AS [blocked_session_count],\r\n DATEDIFF(SECOND, DTAT.transaction_begin_time, GETDATE()) AS [duration_seconds],\r\n CASE \r\n WHEN DTDT.[database_transaction_log_bytes_reserved] = 0 THEN 0\r\n ELSE CAST(((DTDT.[database_transaction_log_bytes_used] * 1.0) / (DTDT.[database_transaction_log_bytes_reserved] * 1.0)) * 100.00 AS DECIMAL(19,2))\r\n END AS [log_bytes_percent_used]\r\n ) fn2\r\nORDER BY fn2.[duration_seconds] DESC, \r\n DER.session_id;"
}
{
"id": "c69f2296-ccb8-4f1f-9b56-8788a51cd9f7",
"prefix": "TDC_Admin_GetVLFCounts",
"description": "",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9816855Z",
"permissions": [],
"body": "/* FOR SQL SERVER 2017 and higher: https://blog.sqlauthority.com/2018/02/18/get-vlf-count-size-sql-server-interview-question-week-161/ */\r\n\r\nSELECT\r\n [s].[name],\r\n [s].[database_id],\r\n COUNT([l].[database_id]) AS [VLF Count],\r\n SUM([l].[vlf_size_mb]) AS [VLF Size (MB)],\r\n SUM(CAST([l].[vlf_active] AS INT)) AS [Active VLF],\r\n SUM([l].[vlf_active] * [l].[vlf_size_mb]) AS [Active VLF Size (MB)],\r\n COUNT([l].[database_id]) - SUM(CAST([l].[vlf_active] AS INT)) AS [In-active VLF],\r\n SUM([l].[vlf_size_mb]) - SUM([l].[vlf_active] * [l].[vlf_size_mb]) AS [In-active VLF Size (MB)]\r\nFROM [sys].[databases] AS [s] \r\nCROSS APPLY [sys].dm_db_log_info([s].[database_id]) AS [l]\r\nGROUP BY\r\n [s].[name],\r\n [s].[database_id]\r\nORDER BY 'VLF Count' DESC;\r\nGO\r\n\r\n/* ALL SQL SERVER VERSIONS */\r\n\r\nIF OBJECT_ID('tempdb..#VLFInfo') IS NOT NULL BEGIN\r\n DROP TABLE [#VLFInfo];\r\nEND\r\nGO\r\n\r\nIF OBJECT_ID('tempdb..#VLFCountResults') IS NOT NULL BEGIN\t\r\n DROP TABLE [#VLFCountResults];\r\nEND\r\nGO\r\n\r\nCREATE TABLE [#VLFInfo] (\r\n [RecoveryUnitId] INT,\r\n [FileID] INT,\r\n [FileSize] BIGINT,\r\n [StartOffset] BIGINT,\r\n [FSeqNo] BIGINT,\r\n [Status] BIGINT,\r\n [Parity] BIGINT,\r\n [CreateLSN] NUMERIC(38)\r\n);\r\n\r\nCREATE TABLE [#VLFCountResults] (\r\n [DatabaseName] sysname,\r\n [VLFCount] INT\r\n);\r\n\r\nEXEC [sys].[sp_MSforeachdb]\r\n N'\r\n\tUSE [?]; \r\n\tINSERT INTO #VLFInfo \r\n\tEXEC sp_executesql N''DBCC LOGINFO([?])''; \r\n\t \r\n\tINSERT INTO #VLFCountResults \r\n\tSELECT DB_NAME(), COUNT(*) \r\n\tFROM #VLFInfo; \r\n\r\n\tTRUNCATE TABLE #VLFInfo;\r\n';\r\n\r\nSELECT\r\n [DatabaseName],\r\n [VLFCount]\r\nFROM [#VLFCountResults]\r\nORDER BY [VLFCount] DESC;\r\n\r\nIF OBJECT_ID('tempdb..#VLFInfo') IS NOT NULL BEGIN\r\n DROP TABLE [#VLFInfo];\r\nEND\r\nGO\r\n\r\nIF OBJECT_ID('tempdb..#VLFCountResults') IS NOT NULL BEGIN\t\r\n DROP TABLE [#VLFCountResults];\r\nEND\r\nGO\r\n"
}
{
"id": "10f5f08c-b799-424e-8e61-17f0a264638e",
"prefix": "TDC_Admin_GetWaitStats",
"description": "",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9816855Z",
"permissions": [],
"body": "WITH [Waits] AS\r\n (SELECT\r\n [wait_type],\r\n [wait_time_ms] / 1000.0 AS [WaitS],\r\n ([wait_time_ms] - [signal_wait_time_ms]) / 1000.0 AS [ResourceS],\r\n [signal_wait_time_ms] / 1000.0 AS [SignalS],\r\n [waiting_tasks_count] AS [WaitCount],\r\n 100.0 * [wait_time_ms] / SUM ([wait_time_ms]) OVER() AS [Percentage],\r\n ROW_NUMBER() OVER(ORDER BY [wait_time_ms] DESC) AS [RowNum]\r\n FROM sys.dm_os_wait_stats\r\n WHERE [wait_type] NOT IN (\r\n N'BROKER_EVENTHANDLER', N'BROKER_RECEIVE_WAITFOR',\r\n N'BROKER_TASK_STOP', N'BROKER_TO_FLUSH',\r\n N'BROKER_TRANSMITTER', N'CHECKPOINT_QUEUE',\r\n N'CHKPT', N'CLR_AUTO_EVENT',\r\n N'CLR_MANUAL_EVENT', N'CLR_SEMAPHORE',\r\n\r\n -- Maybe uncomment these four if you have mirroring issues\r\n N'DBMIRROR_DBM_EVENT', N'DBMIRROR_EVENTS_QUEUE',\r\n N'DBMIRROR_WORKER_QUEUE', N'DBMIRRORING_CMD',\r\n\r\n N'DIRTY_PAGE_POLL', N'DISPATCHER_QUEUE_SEMAPHORE',\r\n N'EXECSYNC', N'FSAGENT',\r\n N'FT_IFTS_SCHEDULER_IDLE_WAIT', N'FT_IFTSHC_MUTEX', \r\n\r\n -- Maybe uncomment these six if you have AG issues\r\n N'HADR_CLUSAPI_CALL', N'HADR_FILESTREAM_IOMGR_IOCOMPLETION',\r\n N'HADR_LOGCAPTURE_WAIT', N'HADR_NOTIFICATION_DEQUEUE',\r\n N'HADR_TIMER_TASK', N'HADR_WORK_QUEUE',\r\n\r\n N'KSOURCE_WAKEUP', N'LAZYWRITER_SLEEP',\r\n N'LOGMGR_QUEUE', N'MEMORY_ALLOCATION_EXT',\r\n N'ONDEMAND_TASK_QUEUE',\r\n N'PREEMPTIVE_XE_GETTARGETSTATE',\r\n N'PWAIT_ALL_COMPONENTS_INITIALIZED',\r\n N'PWAIT_DIRECTLOGCONSUMER_GETNEXT',\r\n N'QDS_PERSIST_TASK_MAIN_LOOP_SLEEP', N'QDS_ASYNC_QUEUE',\r\n N'QDS_CLEANUP_STALE_QUERIES_TASK_MAIN_LOOP_SLEEP',\r\n N'QDS_SHUTDOWN_QUEUE', N'REDO_THREAD_PENDING_WORK',\r\n N'REQUEST_FOR_DEADLOCK_SEARCH', N'RESOURCE_QUEUE',\r\n N'SERVER_IDLE_CHECK', N'SLEEP_BPOOL_FLUSH',\r\n N'SLEEP_DBSTARTUP', N'SLEEP_DCOMSTARTUP',\r\n N'SLEEP_MASTERDBREADY', N'SLEEP_MASTERMDREADY',\r\n N'SLEEP_MASTERUPGRADED', N'SLEEP_MSDBSTARTUP',\r\n N'SLEEP_SYSTEMTASK', N'SLEEP_TASK',\r\n N'SLEEP_TEMPDBSTARTUP', N'SNI_HTTP_ACCEPT',\r\n N'SP_SERVER_DIAGNOSTICS_SLEEP', N'SQLTRACE_BUFFER_FLUSH',\r\n N'SQLTRACE_INCREMENTAL_FLUSH_SLEEP',\r\n N'SQLTRACE_WAIT_ENTRIES', N'WAIT_FOR_RESULTS',\r\n N'WAITFOR', N'WAITFOR_TASKSHUTDOWN',\r\n N'WAIT_XTP_RECOVERY',\r\n N'WAIT_XTP_HOST_WAIT', N'WAIT_XTP_OFFLINE_CKPT_NEW_LOG',\r\n N'WAIT_XTP_CKPT_CLOSE', N'XE_DISPATCHER_JOIN', \r\n N'XE_DISPATCHER_WAIT', N'XE_TIMER_EVENT')\r\n AND [waiting_tasks_count] > 0\r\n )\r\nSELECT\r\n MAX ([W1].[wait_type]) AS [WaitType],\r\n CAST (MAX ([W1].[WaitS]) AS DECIMAL (16,2)) AS [Wait_S],\r\n CAST (MAX ([W1].[ResourceS]) AS DECIMAL (16,2)) AS [Resource_S],\r\n CAST (MAX ([W1].[SignalS]) AS DECIMAL (16,2)) AS [Signal_S],\r\n MAX ([W1].[WaitCount]) AS [WaitCount],\r\n CAST (MAX ([W1].[Percentage]) AS DECIMAL (5,2)) AS [Percentage],\r\n CAST ((MAX ([W1].[WaitS]) / MAX ([W1].[WaitCount])) AS DECIMAL (16,4)) AS [AvgWait_S],\r\n CAST ((MAX ([W1].[ResourceS]) / MAX ([W1].[WaitCount])) AS DECIMAL (16,4)) AS [AvgRes_S],\r\n CAST ((MAX ([W1].[SignalS]) / MAX ([W1].[WaitCount])) AS DECIMAL (16,4)) AS [AvgSig_S],\r\n CAST ('https://www.sqlskills.com/help/waits/' + MAX ([W1].[wait_type]) as XML) AS [Help/Info URL]\r\nFROM [Waits] AS [W1]\r\nINNER JOIN [Waits] AS [W2]\r\n ON [W2].[RowNum] <= [W1].[RowNum]\r\nGROUP BY [W1].[RowNum]\r\nHAVING SUM ([W2].[Percentage]) - MAX( [W1].[Percentage] ) < 95; -- percentage threshold\r\nGO"
}
{
"id": "99c64f8a-343d-4f17-885a-f9203b61f84b",
"prefix": "TDC_Admin_GetWaitStatsInfo",
"description": "To Get Wait Statistics Information to Check Where SQL Server Hurts",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9826852Z",
"permissions": [],
"body": "/* =========================================================================================================================================\r\n-- Server\t\t: LOCAL SERVER\r\n-- Database\t\t: master\r\n-- Script\t\t: GetWaitStatsInfo\r\n-- Description\t: To Get Wait Statistics(Wait Stats) Information to Check Where SQL Server Hurts\r\n-- Link\t\t\t: https://www.sqlskills.com/blogs/paul/wait-statistics-or-please-tell-me-where-it-hurts/\r\n-- Usage\t\t: Just Execute and UnComment Where Clause if Required.\r\n\t\t\t***** We Can Reset Aggregated Statistics using this code:\r\n\t\t\t\t--DBCC SQLPERF (N'sys.dm_os_wait_stats', CLEAR);\r\n========================================================================================================================================= */\r\nUSE master;\r\nGO\r\n--\r\n;WITH Waits\r\nAS (\r\n\t SELECT wait_type,\r\n\t\t\t wait_time_ms / 1000.0 AS \"WaitS\",\r\n\t\t\t (wait_time_ms - signal_wait_time_ms) / 1000.0 AS \"ResourceS\",\r\n\t\t\t signal_wait_time_ms / 1000.0 AS \"SignalS\",\r\n\t\t\t waiting_tasks_count AS \"WaitCount\",\r\n\t\t\t 100.0 * wait_time_ms / SUM(wait_time_ms) OVER () AS \"Percentage\",\r\n\t\t\t ROW_NUMBER() OVER (ORDER BY wait_time_ms DESC) AS \"RowNum\"\r\n\t FROM sys.dm_os_wait_stats\r\n\t WHERE wait_type NOT IN (\r\n\t\t\t\t\t\t\t\t -- These wait types are almost 100% never a problem and so they are filtered out to avoid them skewing the results. \r\n\t\t\t\t\t\t\t\t -- Click on the URL for more information.\r\n\t\t\t\t\t\t\t\t N'BROKER_EVENTHANDLER',\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/BROKER_EVENTHANDLER\r\n\t\t\t\t\t\t\t\t N'BROKER_RECEIVE_WAITFOR',\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/BROKER_RECEIVE_WAITFOR\r\n\t\t\t\t\t\t\t\t N'BROKER_TASK_STOP',\t\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/BROKER_TASK_STOP\r\n\t\t\t\t\t\t\t\t N'BROKER_TO_FLUSH',\t\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/BROKER_TO_FLUSH\r\n\t\t\t\t\t\t\t\t N'BROKER_TRANSMITTER',\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/BROKER_TRANSMITTER\r\n\t\t\t\t\t\t\t\t N'CHECKPOINT_QUEUE',\t\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/CHECKPOINT_QUEUE\r\n\t\t\t\t\t\t\t\t N'CHKPT',\t\t\t\t\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/CHKPT\r\n\t\t\t\t\t\t\t\t N'CLR_AUTO_EVENT',\t\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/CLR_AUTO_EVENT\r\n\t\t\t\t\t\t\t\t N'CLR_MANUAL_EVENT',\t\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/CLR_MANUAL_EVENT\r\n\t\t\t\t\t\t\t\t N'CLR_SEMAPHORE',\t\t\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/CLR_SEMAPHORE\r\n\t\t\t\t\t\t\t\t-- Maybe comment this out if you have parallelism issues\r\n\t\t\t\t\t\t\t\t N'CXCONSUMER',\t\t\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/CXCONSUMER\r\n\t\t\t\t\t\t\t\t-- Maybe comment these four out if you have mirroring issues\r\n\t\t\t\t\t\t\t\t N'DBMIRROR_DBM_EVENT',\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/DBMIRROR_DBM_EVENT\r\n\t\t\t\t\t\t\t\t N'DBMIRROR_EVENTS_QUEUE',\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/DBMIRROR_EVENTS_QUEUE\r\n\t\t\t\t\t\t\t\t N'DBMIRROR_WORKER_QUEUE',\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/DBMIRROR_WORKER_QUEUE\r\n\t\t\t\t\t\t\t\t N'DBMIRRORING_CMD',\t\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/DBMIRRORING_CMD\r\n\t\t\t\t\t\t\t\t N'DIRTY_PAGE_POLL',\t\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/DIRTY_PAGE_POLL\r\n\t\t\t\t\t\t\t\t N'DISPATCHER_QUEUE_SEMAPHORE',\t\t\t\t\t -- https://www.sqlskills.com/help/waits/DISPATCHER_QUEUE_SEMAPHORE\r\n\t\t\t\t\t\t\t\t N'EXECSYNC',\t\t\t\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/EXECSYNC\r\n\t\t\t\t\t\t\t\t N'FSAGENT',\t\t\t\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/FSAGENT\r\n\t\t\t\t\t\t\t\t N'FT_IFTS_SCHEDULER_IDLE_WAIT',\t\t\t\t\t -- https://www.sqlskills.com/help/waits/FT_IFTS_SCHEDULER_IDLE_WAIT\r\n\t\t\t\t\t\t\t\t N'FT_IFTSHC_MUTEX',\t\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/FT_IFTSHC_MUTEX\r\n\t\t\t\t\t\t\t\t-- Maybe comment these six out if you have AG issues\r\n\t\t\t\t\t\t\t\t N'HADR_CLUSAPI_CALL',\t\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/HADR_CLUSAPI_CALL\r\n\t\t\t\t\t\t\t\t N'HADR_FILESTREAM_IOMGR_IOCOMPLETION',\t\t\t -- https://www.sqlskills.com/help/waits/HADR_FILESTREAM_IOMGR_IOCOMPLETION\r\n\t\t\t\t\t\t\t\t N'HADR_LOGCAPTURE_WAIT',\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/HADR_LOGCAPTURE_WAIT\r\n\t\t\t\t\t\t\t\t N'HADR_NOTIFICATION_DEQUEUE',\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/HADR_NOTIFICATION_DEQUEUE\r\n\t\t\t\t\t\t\t\t N'HADR_TIMER_TASK',\t\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/HADR_TIMER_TASK\r\n\t\t\t\t\t\t\t\t N'HADR_WORK_QUEUE',\t\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/HADR_WORK_QUEUE\r\n\t\t\t\t\t\t\t\t N'KSOURCE_WAKEUP',\t\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/KSOURCE_WAKEUP\r\n\t\t\t\t\t\t\t\t N'LAZYWRITER_SLEEP',\t\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/LAZYWRITER_SLEEP\r\n\t\t\t\t\t\t\t\t N'LOGMGR_QUEUE',\t\t\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/LOGMGR_QUEUE\r\n\t\t\t\t\t\t\t\t N'MEMORY_ALLOCATION_EXT',\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/MEMORY_ALLOCATION_EXT\r\n\t\t\t\t\t\t\t\t N'ONDEMAND_TASK_QUEUE',\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/ONDEMAND_TASK_QUEUE\r\n\t\t\t\t\t\t\t\t N'PARALLEL_REDO_DRAIN_WORKER',\t\t\t\t\t -- https://www.sqlskills.com/help/waits/PARALLEL_REDO_DRAIN_WORKER\r\n\t\t\t\t\t\t\t\t N'PARALLEL_REDO_LOG_CACHE',\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/PARALLEL_REDO_LOG_CACHE\r\n\t\t\t\t\t\t\t\t N'PARALLEL_REDO_TRAN_LIST',\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/PARALLEL_REDO_TRAN_LIST\r\n\t\t\t\t\t\t\t\t N'PARALLEL_REDO_WORKER_SYNC',\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/PARALLEL_REDO_WORKER_SYNC\r\n\t\t\t\t\t\t\t\t N'PARALLEL_REDO_WORKER_WAIT_WORK',\t\t\t\t -- https://www.sqlskills.com/help/waits/PARALLEL_REDO_WORKER_WAIT_WORK\r\n\t\t\t\t\t\t\t\t N'PREEMPTIVE_OS_FLUSHFILEBUFFERS',\t\t\t\t -- https://www.sqlskills.com/help/waits/PREEMPTIVE_OS_FLUSHFILEBUFFERS\r\n\t\t\t\t\t\t\t\t N'PREEMPTIVE_XE_GETTARGETSTATE',\t\t\t\t\t -- https://www.sqlskills.com/help/waits/PREEMPTIVE_XE_GETTARGETSTATE\r\n\t\t\t\t\t\t\t\t N'PVS_PREALLOCATE',\t\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/PVS_PREALLOCATE\r\n\t\t\t\t\t\t\t\t N'PWAIT_ALL_COMPONENTS_INITIALIZED',\t\t\t\t -- https://www.sqlskills.com/help/waits/PWAIT_ALL_COMPONENTS_INITIALIZED\r\n\t\t\t\t\t\t\t\t N'PWAIT_DIRECTLOGCONSUMER_GETNEXT',\t\t\t\t -- https://www.sqlskills.com/help/waits/PWAIT_DIRECTLOGCONSUMER_GETNEXT\r\n\t\t\t\t\t\t\t\t N'QDS_PERSIST_TASK_MAIN_LOOP_SLEEP',\t\t\t\t -- https://www.sqlskills.com/help/waits/QDS_PERSIST_TASK_MAIN_LOOP_SLEEP\r\n\t\t\t\t\t\t\t\t N'QDS_ASYNC_QUEUE',\t\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/QDS_ASYNC_QUEUE\r\n\t\t\t\t\t\t\t\t N'QDS_CLEANUP_STALE_QUERIES_TASK_MAIN_LOOP_SLEEP', -- https://www.sqlskills.com/help/waits/QDS_CLEANUP_STALE_QUERIES_TASK_MAIN_LOOP_SLEEP\r\n\t\t\t\t\t\t\t\t N'QDS_SHUTDOWN_QUEUE',\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/QDS_SHUTDOWN_QUEUE\r\n\t\t\t\t\t\t\t\t N'REDO_THREAD_PENDING_WORK',\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/REDO_THREAD_PENDING_WORK\r\n\t\t\t\t\t\t\t\t N'REQUEST_FOR_DEADLOCK_SEARCH',\t\t\t\t\t -- https://www.sqlskills.com/help/waits/REQUEST_FOR_DEADLOCK_SEARCH\r\n\t\t\t\t\t\t\t\t N'RESOURCE_QUEUE',\t\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/RESOURCE_QUEUE\r\n\t\t\t\t\t\t\t\t N'SERVER_IDLE_CHECK',\t\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/SERVER_IDLE_CHECK\r\n\t\t\t\t\t\t\t\t N'SLEEP_BPOOL_FLUSH',\t\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/SLEEP_BPOOL_FLUSH\r\n\t\t\t\t\t\t\t\t N'SLEEP_DBSTARTUP',\t\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/SLEEP_DBSTARTUP\r\n\t\t\t\t\t\t\t\t N'SLEEP_DCOMSTARTUP',\t\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/SLEEP_DCOMSTARTUP\r\n\t\t\t\t\t\t\t\t N'SLEEP_MASTERDBREADY',\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/SLEEP_MASTERDBREADY\r\n\t\t\t\t\t\t\t\t N'SLEEP_MASTERMDREADY',\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/SLEEP_MASTERMDREADY\r\n\t\t\t\t\t\t\t\t N'SLEEP_MASTERUPGRADED',\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/SLEEP_MASTERUPGRADED\r\n\t\t\t\t\t\t\t\t N'SLEEP_MSDBSTARTUP',\t\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/SLEEP_MSDBSTARTUP\r\n\t\t\t\t\t\t\t\t N'SLEEP_SYSTEMTASK',\t\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/SLEEP_SYSTEMTASK\r\n\t\t\t\t\t\t\t\t N'SLEEP_TASK',\t\t\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/SLEEP_TASK\r\n\t\t\t\t\t\t\t\t N'SLEEP_TEMPDBSTARTUP',\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/SLEEP_TEMPDBSTARTUP\r\n\t\t\t\t\t\t\t\t N'SNI_HTTP_ACCEPT',\t\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/SNI_HTTP_ACCEPT\r\n\t\t\t\t\t\t\t\t N'SOS_WORK_DISPATCHER',\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/SOS_WORK_DISPATCHER\r\n\t\t\t\t\t\t\t\t N'SP_SERVER_DIAGNOSTICS_SLEEP',\t\t\t\t\t -- https://www.sqlskills.com/help/waits/SP_SERVER_DIAGNOSTICS_SLEEP\r\n\t\t\t\t\t\t\t\t N'SQLTRACE_BUFFER_FLUSH',\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/SQLTRACE_BUFFER_FLUSH\r\n\t\t\t\t\t\t\t\t N'SQLTRACE_INCREMENTAL_FLUSH_SLEEP',\t\t\t\t -- https://www.sqlskills.com/help/waits/SQLTRACE_INCREMENTAL_FLUSH_SLEEP\r\n\t\t\t\t\t\t\t\t N'SQLTRACE_WAIT_ENTRIES',\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/SQLTRACE_WAIT_ENTRIES\r\n\t\t\t\t\t\t\t\t N'VDI_CLIENT_OTHER',\t\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/VDI_CLIENT_OTHER\r\n\t\t\t\t\t\t\t\t N'WAIT_FOR_RESULTS',\t\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/WAIT_FOR_RESULTS\r\n\t\t\t\t\t\t\t\t N'WAITFOR',\t\t\t\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/WAITFOR\r\n\t\t\t\t\t\t\t\t N'WAITFOR_TASKSHUTDOWN',\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/WAITFOR_TASKSHUTDOWN\r\n\t\t\t\t\t\t\t\t N'WAIT_XTP_RECOVERY',\t\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/WAIT_XTP_RECOVERY\r\n\t\t\t\t\t\t\t\t N'WAIT_XTP_HOST_WAIT',\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/WAIT_XTP_HOST_WAIT\r\n\t\t\t\t\t\t\t\t N'WAIT_XTP_OFFLINE_CKPT_NEW_LOG',\t\t\t\t\t -- https://www.sqlskills.com/help/waits/WAIT_XTP_OFFLINE_CKPT_NEW_LOG\r\n\t\t\t\t\t\t\t\t N'WAIT_XTP_CKPT_CLOSE',\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/WAIT_XTP_CKPT_CLOSE\r\n\t\t\t\t\t\t\t\t N'XE_DISPATCHER_JOIN',\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/XE_DISPATCHER_JOIN\r\n\t\t\t\t\t\t\t\t N'XE_DISPATCHER_WAIT',\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/XE_DISPATCHER_WAIT\r\n\t\t\t\t\t\t\t\t N'XE_TIMER_EVENT'\t\t\t\t\t\t\t\t\t -- https://www.sqlskills.com/help/waits/XE_TIMER_EVENT\r\n\t\t\t\t\t\t\t )\r\n\t\t\t AND waiting_tasks_count > 0\r\n )\r\nSELECT MAX(W1.wait_type) AS \"WaitType\",\r\n\t CAST(MAX(W1.WaitS) AS DECIMAL(16, 2)) AS \"Wait_S\",\r\n\t CAST(MAX(W1.ResourceS) AS DECIMAL(16, 2)) AS \"Resource_S\",\r\n\t CAST(MAX(W1.SignalS) AS DECIMAL(16, 2)) AS \"Signal_S\",\r\n\t MAX(W1.WaitCount) AS \"WaitCount\",\r\n\t CAST(MAX(W1.Percentage) AS DECIMAL(5, 2)) AS \"Percentage\",\r\n\t CAST((MAX(W1.WaitS) / MAX(W1.WaitCount)) AS DECIMAL(16, 4)) AS \"AvgWait_S\",\r\n\t CAST((MAX(W1.ResourceS) / MAX(W1.WaitCount)) AS DECIMAL(16, 4)) AS \"AvgRes_S\",\r\n\t CAST((MAX(W1.SignalS) / MAX(W1.WaitCount)) AS DECIMAL(16, 4)) AS \"AvgSig_S\",\r\n\t CAST('https://www.sqlskills.com/help/waits/' + MAX(W1.wait_type) AS XML) AS \"Help/Info URL\"\r\nFROM Waits AS W1\r\nINNER JOIN Waits AS W2 ON W2.RowNum <= W1.RowNum\r\n--WHERE W1.wait_type LIKE '%IO%'\r\nGROUP BY W1.RowNum\r\nHAVING (SUM(W2.Percentage) - MAX(W1.Percentage)) < 95; -- Percentage Threshold\r\nGO"
}
{
"id": "e01ba7f3-4c7c-4b30-953a-f00f153b9613",
"prefix": "TDC_Admin_GetXMLdataFromDataAuditTbl",
"description": "GetXMLdata From DBAudit.dbo.DataAuditTbl",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9826852Z",
"permissions": [],
"body": "/* =========================================================================================================================================\r\n-- Server\t\t: LOCAL SERVER\r\n-- Database\t\t: DBaudit\r\n-- Script\t\t: GetXMLdataFromDataAuditTbl\r\n-- Description\t: GetXMLdata From DBaudit.dbo.DataAuditTbl\r\n-- Usage\t\t: Once DML Triggers are Created and Modifications will be captured in DBaudit.dbo.DataAuditTbl as XML in DMLchange Column\r\n\t\t\t\t\tSo, To Read the XML Data, the Below Query will be helpful.\r\n========================================================================================================================================= */\r\nUSE DBaudit;\r\nGO\r\n--\r\n--/*SELECT * FROM DBaudit.dbo.DataAuditTbl;*/\r\nDECLARE @ID INT = $id$; -- Get Xid from DBaudit.dbo.DataAuditTbl\r\n--\r\nDECLARE @XMLdata XML;\r\nSELECT @XMLdata = DMLchange FROM DBaudit.dbo.DataAuditTbl WHERE Xid = @ID;\r\n--PRINT CONVERT(VARCHAR(MAX), @XMLdata);\r\n--\r\n--$BeginRegion: Analysing Data in @XMLdata\r\n----$BeginRegion: Retriving ColumnNames from @XMLdata\r\nDECLARE @TableColumns VARCHAR(MAX) = '';\r\nSELECT @TableColumns = SUBSTRING((\tSELECT ', ' + QUOTENAME(S.Att_Id)\r\n\t\t\t\t\t\t\t\t\tFROM (\r\n\t\t\t\t\t\t\t\t\t\t\tSELECT DENSE_RANK() OVER (ORDER BY p.parent) AS \"Id\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t child.value('local-name(.)', 'NVARCHAR(256)') AS \"Att_Id\"\r\n\t\t\t\t\t\t\t\t\t\t\tFROM @XMLdata.nodes('/TableHeader/row') AS p(parent)\r\n\t\t\t\t\t\t\t\t\t\t\tCROSS APPLY p.parent.nodes('./*') AS c(child)\r\n\t\t\t\t\t\t\t\t\t\t ) AS S\r\n\t\t\t\t\t\t\t\t\tWHERE S.Id = 1\r\n\t\t\t\t\t\t\t\t\tFOR XML PATH('')), 2, 200000);\r\n--SELECT @TableColumns;\r\n----$EndRegion: Retriving ColumnNames from @XMLdata\r\n--\r\n----$BeginRegion: Visualising @XMLdata as Tabular Format\r\nDECLARE @SQLstring NVARCHAR(MAX) = N'';\r\nSET @SQLstring = --\r\nN'SELECT ' + @TableColumns + N'\r\nFROM\r\n(\r\n\tSELECT DENSE_RANK() OVER (ORDER BY p.parent) AS \"Id\",\r\n\t\t child.value(''local-name(.)'', ''NVARCHAR(256)'') AS \"Att_Id\",\r\n\t\t child.value(''.'', ''VARCHAR(MAX)'') AS \"Att_Value\"\r\n\tFROM @XMLdata.nodes(''/TableHeader/row'') AS p(parent)\r\n\tCROSS APPLY p.parent.nodes(''./*'') AS c(child)\r\n) AS \"Source\"\r\nPIVOT\r\n(\r\n\tMAX(Att_Value)\r\n\tFOR Att_Id IN (' + @TableColumns + N')\r\n) AS \"Target\";';\r\n--PRINT @SQLstring;\r\nEXEC sys.sp_executesql @command = @SQLstring, @params = N'@XMLdata XML', @XMLdata = @XMLdata;\r\n----$EndRegion: Visualising @XMLdata as Tabular Format\r\n--$EndRegion: Analysing Data in @XMLdata",
"placeholders": [
{
"name": "id",
"defaultValue": null
}
]
}
{
"id": "9eba2c26-569e-4ef3-9aa1-4444126e09ff",
"prefix": "TDC_Admin_InEfficientQueries",
"description": "",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9826852Z",
"permissions": [],
"body": "/*\r\n\tAuthor: Tim Cartwright\r\n\t1) Leave the @dbname variable empty or null for all databases\r\n\t2) Changed the @dbname variable to a specific variable to only get the queries for that database.\r\n\tRETURNS: The queries with the highest cost, and longest working time with the worst offenders being at the top of the list.\r\n*/\r\n\r\n\r\nDECLARE @dbname sysname = '', -- '',\r\n\t@for_excel bit = 0\r\n\r\n;WITH XMLNAMESPACES (DEFAULT 'http://schemas.microsoft.com/sqlserver/2004/07/showplan')\r\n\tSELECT \r\n\t\t[db_name] = CAST(DB_NAME(qinfo.dbid) AS varchar(128)),\r\n\t\t[text] = CASE WHEN @for_excel = 1 THEN '\"' + qinfo.[text] + '\"' ELSE qinfo.[text] END, \r\n\t\t[param_select] = CASE WHEN @for_excel = 1 THEN '\"' + fnParams.[param_select] + '\"' ELSE fnParams.[param_select] END,\r\n\t\tquery_plan = CASE WHEN @for_excel = 1 THEN NULL ELSE qp.query_plan END,\r\n\t\t[impact_weight] = CAST(fnWeight.[impact_weight] AS decimal(19, 4)),\r\n\t\t[highest_statement_cost] = CAST(fnCosts.HighestStatementCost AS decimal(19, 2)),\r\n\t\tqinfo.[execution_count],\r\n\t\t[executions_per_minute] = CAST(qinfo.[executions_per_minute] AS decimal(19, 4)),\r\n\t\t[executions_per_hour] = CAST(qinfo.[executions_per_hour] AS decimal(19, 4)),\r\n\t\t[average_worker_time] = CONVERT(varchar(30), DATEADD(millisecond, (qinfo.[average_worker_time] / 1000.0), 0), 114), -- 108 for no milliseconds, 114 with\r\n\t\t[average_execution_time] = CONVERT(varchar(30), DATEADD(millisecond, (qinfo.[average_exec_time] / 1000.0), 0), 114),\r\n\t\tqinfo.[average_used_threads],\r\n\t\tqinfo.[average_logical_reads],\r\n\t\t[average_logical_reads_mb] = CAST((qinfo.[average_logical_reads] / 128.0) AS decimal(19, 2)),\r\n\t\tqinfo.[average_logical_writes],\r\n\t\t[average_logical_writes_mb] = CAST((qinfo.[average_logical_writes] / 128.0) AS decimal(19, 2)),\r\n\t\tqinfo.[max_physical_reads],\r\n\t\t[max_physical_reads_mb] = CAST((qinfo.[max_physical_reads] / 128.0) AS decimal(19, 2)), -- size of the querys data in memory\r\n\t\t[average_used_memory_grant_mb] = CAST((qinfo.[average_used_memory_grant] / 1024.0) AS decimal(19, 2)), \r\n\t\t[average_memory_grant_mb] = CAST((qinfo.[average_memory_grant] / 1024.0) AS decimal(19, 2)),\r\n\t\tqinfo.[plan_creation_time],\r\n\t\tqinfo.[last_execution_time],\r\n\t\tqinfo.[query_hash],\r\n\t\tqinfo.[sql_handle],\r\n\t\tqinfo.[plan_handle],\r\n\t\tqinfo.[min_logical_reads], \r\n\t\tqinfo.[max_logical_reads]\r\n\tFROM (\t\r\n\t\tSELECT qs.sql_handle, qs.plan_handle, fnExecCnt.[execution_count], \r\n\t\t\tqs.total_worker_time, qs.total_logical_reads, \r\n\t\t\tqs.total_logical_writes, qt.text, fnStats.average_worker_time, \r\n\t\t\tfnStats.average_logical_reads, fnStats.average_logical_writes, \r\n\t\t\tqt.dbid, fnStats.[average_exec_time], fnStats.[average_used_memory_grant], \r\n\t\t\tfnStats.[average_memory_grant], fnExecs.[executions_per_minute],\r\n\t\t\tfnStats.[average_used_threads], qs.[query_hash],\r\n\t\t\t[plan_creation_time] = COALESCE(fnAge.[cached_time], qs.[creation_time]),\r\n\t\t\tqs.[last_execution_time], fnExecs.[executions_per_hour], \r\n\t\t\tqs.[min_logical_reads], qs.[max_logical_reads], qs.[max_physical_reads]\r\n\t\tFROM sys.dm_exec_query_stats qs\r\n\t\tCROSS APPLY sys.dm_exec_sql_text(qs.plan_handle) as qt\r\n\t\tCROSS APPLY (\r\n\t\t\t--we may have a zero logical read, so at least one of the reads did not return data for whatever reason,\r\n\t\t\t--so adjust the execution count so as to hopefully not skew the stats as much. Sadly, we can not account for all zeros.\r\n\t\t\tSELECT [execution_count] = CASE \r\n\t\t\t\tWHEN qs.[execution_count] <= 1 THEN qs.[execution_count] \r\n\t\t\t\tWHEN qs.[min_logical_reads] = 0 THEN qs.[execution_count] - 1 \r\n\t\t\t\tELSE qs.[execution_count] \r\n\t\t\tEND\r\n\t\t) fnExecCnt\r\n\t\tOUTER APPLY (\r\n\t\t\tSELECT [age_minutes] = CASE \r\n\t\t\t\t\tWHEN DATEDIFF(mi, ps.cached_time, GETDATE()) > 0 AND ps.[execution_count] > 1 THEN DATEDIFF(mi, ps.cached_time, GETDATE()) \r\n ELSE NULL \r\n\t\t\t\tEND,\r\n\t\t\t\tps.cached_time \r\n\t\t\tFROM sys.dm_exec_procedure_stats ps WHERE ps.[plan_handle] = qs.[plan_handle]\r\n\t\t) fnAge\r\n\t\tCROSS APPLY (\r\n\t\t\tSELECT [executions_per_minute] = \r\n\t\t\t\tCASE WHEN fnExecCnt.[execution_count] = 0 THEN 0\r\n\t\t\t\t\t/* we want a exec per min but we dont want zero when the time span is less than 1 minute, so take exec count */\r\n\t\t\t\t\tWHEN COALESCE(fnAge.age_minutes, DATEDIFF(minute, qs.[creation_time], GETDATE()), 0) = 0 THEN fnExecCnt.[execution_count] \r\n\t\t\t\t\tELSE (1.00 * fnExecCnt.[execution_count] / COALESCE(fnAge.age_minutes, DATEDIFF(minute, qs.[creation_time], GETDATE())))\r\n\t\t\t\tEND,\r\n\t\t\t\t[executions_per_hour] = \r\n\t\t\t\tCASE WHEN fnExecCnt.[execution_count] = 0 THEN 0\r\n\t\t\t\t\tWHEN COALESCE(fnAge.age_minutes, DATEDIFF(hour, qs.[creation_time], GETDATE()), 0) = 0 THEN fnExecCnt.[execution_count]\r\n\t\t\t\t\tELSE (1.00 * fnExecCnt.[execution_count] / COALESCE(fnAge.age_minutes / 60.0, DATEDIFF(hour, qs.[creation_time], GETDATE())))\r\n\t\t\t\tEND\r\n\t\t) fnExecs\r\n\t\tCROSS APPLY ( SELECT\r\n\t\t\t[average_worker_time] = qs.total_worker_time / fnExecCnt.[execution_count],\r\n\t\t\t[average_logical_reads] = qs.total_logical_reads / fnExecCnt.[execution_count],\r\n\t\t\t[average_logical_writes] = qs.total_logical_writes / fnExecCnt.[execution_count],\r\n\t\t\t[average_exec_time] = qs.total_elapsed_time / fnExecCnt.[execution_count],\r\n\t\t\t[average_used_memory_grant] = qs.total_used_grant_kb / fnExecCnt.[execution_count],\r\n\t\t\t[average_memory_grant] = qs.total_grant_kb / fnExecCnt.[execution_count],\r\n\t\t\t[average_used_threads] = [qs].[total_used_threads] / fnExecCnt.[execution_count]\r\n\t\t) fnStats\r\n\t\tWHERE (LEN(@dbname) = 0 OR qt.dbid = DB_ID(@dbname)) \r\n\t\t\t--AND qs.[execution_count] >= 2\r\n\t\t\tAND (\t\r\n\t\t\t\tfnStats.[average_worker_time] >= 5000 -- microseconds or 5 milliseconds\r\n\t\t\t\tOR fnStats.[average_exec_time] >= 5000 -- microseconds or 5 milliseconds\r\n\t\t\t)\r\n\t\t\tAND qt.dbid > 4\r\n\t\t\tAND qt.text NOT LIKE '%Inefficient Query Plans Query%' -- leave this in place so this beast does not show in the results.\r\n\t) qinfo\r\n\tCROSS APPLY sys.dm_exec_query_plan(qinfo.plan_handle) AS qp\r\n\tCROSS APPLY ( \r\n\t\t-- find the max statement cost for all the queries in the plan as each plan can contain multiple queries with individual costs\r\n\t\tSELECT [HighestStatementCost] = MAX(cast(ISNULL(stmts.cost.value('@StatementSubTreeCost', 'VARCHAR(128)'), 0) as float)) \r\n\t\tFROM qp.query_plan.nodes('/ShowPlanXML/BatchSequence//StmtSimple') AS stmts(cost)\r\n\t) fnCosts\r\n\tOUTER APPLY (\r\n\t\t--extract the parameters from the plan as xml to make it easier to find them later on\r\n\t\tSELECT [param_select] = 'SELECT ' + REPLACE(STUFF((\r\n\t\t\tSELECT CONCAT(', ', t1.[Column], ' = ', REPLACE(REPLACE(t1.[Value], '(', ''), ')', ''), '##CRLF##') \r\n\t\t\tFROM (\r\n\t\t\t\tSELECT [Column] = CAST(stmts.stmt.value('@Column', 'varchar(8000)') AS varchar(8000)), \r\n\t\t\t\t\t[Value] = CAST(stmts.stmt.value('@ParameterCompiledValue', 'varchar(8000)') AS varchar(8000))\r\n\t\t\t\tFROM qp.query_plan.nodes('/ShowPlanXML/BatchSequence/Batch/Statements//ParameterList/ColumnReference') AS stmts(stmt)\r\n\t\t\t\tWHERE stmts.stmt.value('count(.)', 'int') > 0 \r\n\t\t\t) t1 \r\n\t\t\tGROUP BY t1.[Column], t1.[Value]\r\n\t\t\tORDER BY REPLACE(t1.[Column], '@', '')\r\n\t\t\tFOR XML PATH('') --, ROOT('Parameters')\r\n\t\t), 1, 2, ''), '##CRLF##', CONCAT(CHAR(13), CHAR(10), CHAR(9)))\r\n\t) fnParams\r\n\tCROSS APPLY (\r\n\t\t--come up with an arbitrary weighting system for sorting\r\n\t\t-- using a standard divisor for the larger numbers to keep from number overflow when they are all multiplied together\r\n\t\tSELECT [impact_weight] = \r\n\t\t\t (fnCosts.[HighestStatementCost] * 1.0) \r\n\t\t\t+ (qinfo.[average_worker_time] * 1.0) \r\n\t\t\t+ (qinfo.[average_logical_reads] * 10.0) \r\n\t\t\t+ (qinfo.[executions_per_minute] * 10.0) \r\n\t) fnWeight\r\n\tWHERE fnCosts.HighestStatementCost >= 10 \r\n\tORDER BY fnWeight.[impact_weight] DESC, \r\n\t\tfnCosts.HighestStatementCost DESC"
}
{
"id": "211255b3-483a-4529-989a-53c1f4d3736c",
"prefix": "TDC_Admin_KillSessions",
"description": "Kill Specific Database All Sessions",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9836855Z",
"permissions": [],
"body": "--$BeginRegion: Kill Specific Database All Sessions\r\nPRINT N'--KILLING SPIDs in \"$database_name$\"'\r\nDECLARE @KillSPIDs NVARCHAR(MAX) = N'';\r\nSELECT @KillSPIDs = @KillSPIDs + CHAR(10) + N'Kill ' + CONVERT(VARCHAR(5), session_id) + N';'\r\nFROM sys.dm_exec_sessions \r\nWHERE session_id > 50 AND session_id <> @@SPID AND DB_NAME(database_id) = '$database_name$';\r\n--PRINT @KillSPIDs;\r\nEXEC sys.sp_executesql @statement = @KillSPIDs;\r\n--$EndRegion: Kill Specific Database All Sessions",
"placeholders": [
{
"name": "database_name",
"defaultValue": null
}
]
}
{
"id": "1bdd57b1-ff8d-4045-8061-67fbb1c68523",
"prefix": "TDC_Admin_ListCrossDatabaseDependencies",
"description": "",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9836855Z",
"permissions": [],
"body": "IF OBJECT_ID('tempdb..#CrossDbRefs') IS NOT NULL BEGIN\r\n\tDROP TABLE #CrossDbRefs\r\nEND\r\n\r\nCREATE TABLE [#CrossDbRefs](\r\n\t[referencing_database_name] SYSNAME NOT NULL,\r\n\t[referencing_object] SYSNAME NULL,\r\n\t[referencing_object_type] VARCHAR(20) NULL,\r\n\t[referenced_database_name] SYSNAME NULL,\r\n\t[referenced_entity_name] SYSNAME NULL\r\n);\r\n\r\nINSERT INTO #CrossDbRefs\r\n\t( [referencing_database_name], [referencing_object], [referencing_object_type], [referenced_database_name], [referenced_entity_name] )\r\nEXEC [sys].[sp_MSforeachdb]\t@command1 = N'\r\n\tUSE [?]\r\n\tIF DB_ID() <= 4 RETURN\r\n\t\t\r\n\tSELECT \r\n\t\tDBName = DB_NAME(), \r\n\t\treferencing_object = CONCAT(OBJECT_SCHEMA_NAME (sed.referencing_id), ''.'', OBJECT_NAME (sed.referencing_id)), \r\n\t\t[referencing_object_type] = cast(OBJECTPROPERTYEX(sed.[referencing_id], ''BaseType'') AS varchar(20)),\r\n\t\tsed.referenced_database_name, \r\n\t\tCONCAT(sed.referenced_schema_name, ''.'', sed.referenced_entity_name) \r\n\tFROM sys.sql_expression_dependencies sed\r\n\tWHERE sed.referenced_database_name IS NOT NULL\r\n\t\tAND sed.is_ambiguous = 0\r\n\t\tAND sed.referenced_database_name <> DB_NAME()\r\n'\r\n\r\nSELECT * FROM #CrossDbRefs\r\n\r\nIF OBJECT_ID('tempdb..#CrossDbRefs') IS NOT NULL BEGIN\r\n\tDROP TABLE #CrossDbRefs\r\nEND"
}
{
"id": "323e52c0-ec4a-4bf4-b189-26bbeee793eb",
"prefix": "TDC_Admin_ListUsersPermissions",
"description": "",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9836855Z",
"permissions": [],
"body": "DECLARE @sql NVARCHAR(MAX) = 'SELECT ' + \r\n STUFF((SELECT TOP 100 PERCENT ', [is_' + sp.name + '] = ' + 'IS_SRVROLEMEMBER(''' + sp.name + ''')' \r\n\tFROM sys.server_principals sp WHERE type = 'R' ORDER BY sp.is_fixed_role DESC, sp.create_date FOR XML PATH('')), 1, 2, '')\r\n\r\nEXEC (@sql)\r\n\r\nSET @sql = 'SELECT ' + \r\n STUFF((SELECT TOP 100 PERCENT ', [is_' + dp.name + '] = ' + 'IS_MEMBER(''' + dp.name + ''')' \r\n\tFROM sys.database_principals dp WHERE type = 'R' ORDER BY dp.sid FOR XML PATH('')), 1, 2, '')\r\n\r\nEXEC (@sql)\r\n\t\r\nSELECT * FROM (\t\r\n-- GET THE SERVER PERMISSIONS\r\n\tSELECT p.entity_name, \r\n\t\t[type] = p.entity_name, \r\n\t\tp.permission_name \r\n\tFROM fn_my_permissions (NULL, 'SERVER') p\r\n---------------------\r\n\t\tUNION \r\n---------------------\r\n-- GET THE DATABASE PERMISSIONS\r\n\tSELECT p.entity_name, \r\n\t\t[type] = p.entity_name, \r\n\t\tp.permission_name \r\n\tFROM fn_my_permissions (NULL, 'DATABASE') p\r\n---------------------\r\n\t\tUNION \r\n---------------------\r\n-- GET THE SCHEMA PERMISSIONS\r\n\tSELECT [entity_name] = QUOTENAME(p.entity_name), \r\n\t\t[type] = 'schema', \r\n\t\tp.permission_name \t\r\n\tFROM sys.[schemas] s \r\n\tINNER JOIN sys.all_objects ao ON [s].[schema_id] = [ao].[schema_id]\r\n\tOUTER APPLY sys.fn_my_permissions(s.[name], 'SCHEMA') p\r\n\tWHERE OBJECTPROPERTY(ao.[object_id], 'IsMsShipped') = 0 OR s.name = 'dbo'\r\n---------------------\r\n\t\tUNION \r\n---------------------\r\n-- GET THE PERMISSIONS FOR ALL TOP LEVEL OBJECTS\r\n\tSELECT fn.object_name COLLATE DATABASE_DEFAULT, \r\n\t\t[type] = o.type_desc COLLATE DATABASE_DEFAULT, \r\n\t\tp.permission_name \t \r\n\tFROM sys.objects o \r\n\tCROSS APPLY ( \r\n\t\tSELECT [object_name] = QUOTENAME(SCHEMA_NAME(o.schema_id)) + '.' + QUOTENAME(o.name)\r\n\t) fn\r\n\tOUTER APPLY (\r\n\t\t-- only list the top level object permissions\r\n\t\tSELECT * FROM sys.fn_my_permissions(fn.object_name, 'OBJECT') p WHERE p.subentity_name = ''\r\n\t) p\r\n\tWHERE OBJECTPROPERTY(o.[object_id], 'IsMsShipped') = 0 \r\n\t\tAND o.type IN ('FN', 'IF', 'P', 'PC', 'U', 'V')\r\n) t\r\nORDER BY CASE \r\n\t\tWHEN t.type = 'server' THEN 0\r\n\t\tWHEN t.type = 'database' THEN 1\r\n\t\tWHEN t.type = 'schema' THEN 2\r\n\t\tELSE 3\r\n\tEND,\r\n\tt.type, \r\n\tt.entity_name,\r\n\tt.permission_name"
}
{
"id": "2c4f5864-4775-4e1e-8435-9bc0938a9a08",
"prefix": "TDC_Admin_PossibleBadOptions",
"description": "",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9846853Z",
"permissions": [],
"body": "--SELECT * FROM sys.databases\r\n\r\nSELECT 'SERVER OPTIONS' AS 'container' \r\n\r\n/*\r\n\tAuthor: Tim Cartwright\r\n\tPurpose: Allows you to check the server, and client SET options\r\n\thttps://docs.microsoft.com/en-us/sql/database-engine/configure-windows/configure-the-user-options-server-configuration-option\r\n\t1\t\tDISABLE_DEF_CNST_CHK\tControls interim or deferred constraint checking.\r\n\t2\t\tIMPLICIT_TRANSACTIONS\tFor dblib network library connections, controls whether a transaction is started implicitly when a statement is executed. The IMPLICIT_TRANSACTIONS setting has no effect on ODBC or OLEDB connections.\r\n\t4\t\tCURSOR_CLOSE_ON_COMMIT\tControls behavior of cursors after a commit operation has been performed.\r\n\t8\t\tANSI_WARNINGS\t\t\tControls truncation and NULL in aggregate warnings.\r\n\t16\t\tANSI_PADDING\t\t\tControls padding of fixed-length variables.\r\n\t32\t\tANSI_NULLS\t\t\t\tControls NULL handling when using equality operators.\r\n\t64\t\tARITHABORT\t\t\t\tTerminates a query when an overflow or divide-by-zero error occurs during query execution.\r\n\t128\t\tARITHIGNORE\t\t\t\tReturns NULL when an overflow or divide-by-zero error occurs during a query.\r\n\t256\t\tQUOTED_IDENTIFIER\t\tDifferentiates between single and double quotation marks when evaluating an expression.\r\n\t512\t\tNOCOUNT\t\t\t\t\tTurns off the message returned at the end of each statement that states how many rows were affected.\r\n\t1024\tANSI_NULL_DFLT_ON\t\tAlters the session's behavior to use ANSI compatibility for nullability. New columns defined without explicit nullability are defined to allow nulls.\r\n\t2048\tANSI_NULL_DFLT_OFF\t\tAlters the session's behavior not to use ANSI compatibility for nullability. New columns defined without explicit nullability do not allow nulls.\r\n\t4096\tCONCAT_NULL_YIELDS_NULL\tReturns NULL when concatenating a NULL value with a string.\r\n\t8192\tNUMERIC_ROUNDABORT\t\tGenerates an error when a loss of precision occurs in an expression.\r\n\t16384\tXACT_ABORT\t\t\t\tRolls back a transaction if a Transact-SQL statement raises a run-time error.\r\n*/\r\n\r\nDECLARE @options TABLE ([name] nvarchar(35), [minimum] int, [maximum] int, [config_value] int, [run_value] int)\r\nDECLARE @optionsCheck TABLE([id] int NOT NULL IDENTITY, [setting_name] varchar(128))\r\nDECLARE @current_value INT;\r\n\r\nINSERT INTO @options ([name], [minimum], [maximum], [config_value], [run_value])\r\nEXEC sp_configure 'user_options';\r\n\r\nSELECT @current_value = [config_value] FROM @options;\r\n--SELECT name, minimum, maximum, config_value, run_value FROM @options\r\n--SELECT @current_value\r\n\r\nIF @current_value > 0 BEGIN\r\n\tINSERT INTO @optionsCheck \r\n\t\t([setting_name]) \r\n\tVALUES\r\n\t\t('DISABLE_DEF_CNST_CHK'),\r\n\t\t('IMPLICIT_TRANSACTIONS'),\r\n\t\t('CURSOR_CLOSE_ON_COMMIT'),\r\n\t\t('ANSI_WARNINGS'),\r\n\t\t('ANSI_PADDING'),\r\n\t\t('ANSI_NULLS'),\r\n\t\t('ARITHABORT'),\r\n\t\t('ARITHIGNORE'),\r\n\t\t('QUOTED_IDENTIFIER'),\r\n\t\t('NOCOUNT'),\r\n\t\t('ANSI_NULL_DFLT_ON'),\r\n\t\t('ANSI_NULL_DFLT_OFF'),\r\n\t\t('CONCAT_NULL_YIELDS_NULL'),\r\n\t\t('NUMERIC_ROUNDABORT'),\r\n\t\t('XACT_ABORT')\r\n\r\n\tSELECT fn.[value], \r\n\t\toc.[setting_name], \r\n\t\t[server_option] = CASE WHEN (@current_value & fn.[value]) = fn.[value] THEN 'X' ELSE '' END\r\n\t\t--,[client_option] = CASE WHEN (@@options & fn.[value]) = fn.[value] THEN 'X' ELSE '' END\r\n\tFROM @optionsCheck oc\r\n\tCROSS APPLY (\r\n\t\tSELECT [value] = CASE WHEN oc.id > 1 THEN POWER(2, oc.id - 1) ELSE 1 END\r\n\t) fn\r\nEND\r\n\r\nSELECT 'SERVER SETTINGS' AS 'container' \r\n-- server options\r\nSELECT \r\n\tfill_factor = MAX(t.global_fill_factor),\r\n\tcross_db_owner_chaining = MAX(t.cross_db_owner_chaining),\r\n\tuser_options = MAX(t.user_options),\r\n\tmax_dop = MAX(t.max_dop),\r\n\tcop = MAX(t.cop),\r\n\tdefault_trace = MAX(t.default_trace),\r\n\tole_automation = MAX(t.ole_automation),\r\n\txp_cmdshell = MAX(t.xp_cmdshell),\r\n\taffinity_mask = MAX(t.affinity_mask),\r\n\taffinity_IO_mask = MAX(t.affinity_IO_mask),\r\n\taffinity64_mask = MAX(t.affinity64_mask),\r\n\taffinity64_IO_mask = MAX(t.affinity64_IO_mask),\r\n\tmax_server_memory_MB = MAX(t.max_server_memory_MB),\r\n\tuser_connections = MAX(t.[user_connections]),\r\n\tlocks = MAX(t.locks)\r\nFROM (\r\n\tSELECT \t\r\n\t\tCASE WHEN c.name = 'fill factor (%)' AND c.value > 0 THEN 'X' ELSE '' END AS [global_fill_factor],\r\n\t\tCASE WHEN c.name = 'cross db ownership chaining' AND c.value = 1 THEN 'X' ELSE '' END AS [cross_db_owner_chaining],\r\n\t\tCASE WHEN c.name = 'user options' AND c.value <> 0 THEN 'X' ELSE '' END AS [user_options],\r\n\t\tCASE WHEN c.name = 'max degree of parallelism' AND c.value = 0 THEN 'X' ELSE '' END AS [max_dop],\r\n\t\tCASE WHEN c.name = 'cost threshold for parallelism' AND c.value <= 20 THEN 'X' ELSE '' END AS [cop],\r\n\t\tCASE WHEN c.name = 'default trace enabled' AND c.value = 0 THEN 'X' ELSE '' END AS [default_trace],\r\n\t\tCASE WHEN c.name = 'Ole Automation Procedures' AND c.value = 1 THEN 'X' ELSE '' END AS [ole_automation],\r\n\t\tCASE WHEN c.name = 'xp_cmdshell' AND c.value = 1 THEN 'X' ELSE '' END AS [xp_cmdshell],\r\n\t\tCASE WHEN c.name = 'affinity mask' AND c.value <> 0 THEN 'X' ELSE '' END AS [affinity_mask],\r\n\t\tCASE WHEN c.name = 'affinity64 mask' AND c.value <> 0 THEN 'X' ELSE '' END AS [affinity64_mask],\r\n\t\tCASE WHEN c.name = 'affinity I/O mask' AND c.value <> 0 THEN 'X' ELSE '' END AS [affinity_IO_mask],\r\n\t\tCASE WHEN c.name = 'affinity64 I/O mask' AND c.value <> 0 THEN 'X' ELSE '' END AS [affinity64_IO_mask],\r\n\t\tCASE WHEN c.name = 'max server memory (MB)' AND c.value <= 2000 THEN 'X' ELSE '' END AS [max_server_memory_MB],\r\n\t\tCASE WHEN c.name = 'user connections' AND c.value <> 0 THEN 'X' ELSE '' END AS [user_connections],\r\n\t\tCASE WHEN c.name = 'locks' AND c.value <> 0 THEN 'X' ELSE '' END AS [locks]\r\n\tFROM sys.configurations c\r\n) t\r\n\r\n-- SELECT * FROM sys.configurations c ORDER BY c.name\r\n\r\nSELECT 'DATABASE FILE GROWTHS' AS 'container' \r\n\r\nIF OBJECT_ID('tempdb..#file_growths') IS NOT NULL BEGIN \r\n\tDROP TABLE #file_growths \r\nEND\r\n\r\nCREATE TABLE #file_growths (\r\n\t[db_name] sysname,\r\n\t[file_name] sysname,\r\n\tgrowth_kb DECIMAL(18,2),\r\n\tgrowth_mb DECIMAL(18,2),\r\n\tis_percent_growth BIT\r\n)\r\n\r\nINSERT INTO #file_growths\r\nEXEC sys.sp_MSforeachdb N' \r\n USE [?]; \r\n\tSELECT [db_name] = DB_NAME(), \r\n\t\t[file_name] = df.name,\r\n\t\tfn.growth_kb, \r\n\t\tfn.growth_mb, \r\n\t\tdf.is_percent_growth\r\n\tFROM sys.database_files df\r\n\tCROSS APPLY (\r\n\t\tSELECT [growth_kb] = df.growth * 8.0,\r\n\t\t\t[growth_mb] = df.growth / 128.0\r\n\t) fn\r\n\tWHERE DB_ID(''?'') > 4 \r\n\t\tAND (\r\n\t\t\tdf.is_percent_growth = 1\r\n\t\t\tOR (\r\n\t\t\t\tdf.growth > 0\r\n\t\t\t\tAND (\r\n\t\t\t\t\tfn.growth_mb < 64 OR fn.growth_mb > 2048\r\n\t\t\t\t)\r\n\t\t\t)\r\n\t\t)'\r\n\r\n-- find databases that have abnormal file growths. \r\nSELECT * FROM #file_growths fg ORDER BY fg.db_name, fg.file_name\r\n\r\nSELECT 'DATABASE' AS 'container' \r\n-- find databases with possible bad options\r\nSELECT name, \r\n\t-- owner is not SA\r\n\tCASE WHEN d.owner_sid <> 0x01 THEN 'X' ELSE '' END AS [owner],\r\n\t-- change the collation to your desired collation\r\n\tCASE WHEN d.collation_name <> 'SQL_Latin1_General_CP1_CI_AS' THEN 'X' ELSE '' END AS collation,\r\n\t-- dbs should never have auto close on\r\n\tCASE WHEN d.is_auto_close_on = 1 THEN 'X' ELSE '' END AS auto_close, \r\n\t-- this should be turned on\r\n\tCASE WHEN d.page_verify_option_desc <> 'CHECKSUM' THEN 'X' ELSE '' END AS page_verify, \r\n\t-- there can be valid reasons for this, but it should be justified\r\n\tCASE WHEN d.is_auto_create_stats_on = 0 THEN 'X' ELSE '' END AS auto_create_stats, \r\n\t-- this should be on, so any object created without setting this setting will have it on by default\r\n\tCASE WHEN d.is_quoted_identifier_on = 0 THEN 'X' ELSE '' END AS quoted_identifier,\r\n\t-- this can cause issues if on with certain types of queries\r\n\tCASE WHEN d.is_numeric_roundabort_on = 1 THEN 'X' ELSE '' END AS numeric_roundabort, \r\n\t-- recursive triggers are a design nightmare and should be avoided\r\n\tCASE WHEN d.is_recursive_triggers_on = 1 THEN 'X' ELSE '' END AS recursive_triggers, \r\n\t-- this should be avoided if possible\r\n\tCASE WHEN d.is_trustworthy_on = 1 THEN 'X' ELSE '' END AS trustworthy\r\n\t--, * \r\nFROM sys.databases d\r\nWHERE d.database_id NOT IN (1, 2, 4)\r\n\tAND (\r\n\t\td.owner_sid <> 0x01 \r\n\t\tOR d.collation_name <> 'SQL_Latin1_General_CP1_CI_AS'\r\n\t\tOR d.is_auto_close_on = 1\r\n\t\tOR d.page_verify_option_desc <> 'CHECKSUM' \r\n\t\tOR d.is_auto_create_stats_on = 0 \r\n\t\tOR d.is_quoted_identifier_on = 0 \r\n\t\tOR d.is_numeric_roundabort_on = 1\r\n\t\tOR d.is_recursive_triggers_on = 1\r\n\t\tOR d.is_trustworthy_on = 1 \r\n\t)\r\nORDER BY d.name\r\n\r\nSELECT 'TABLES' AS 'container' \r\nIF OBJECT_ID('tempdb..#table_options') IS NOT NULL BEGIN \r\n\tDROP TABLE #table_options \r\nEND\r\n\r\nCREATE TABLE #table_options (\r\n\t[db_name] sysname,\r\n\t[table_name] sysname,\r\n\tuses_ansi_nulls CHAR(1)\r\n)\r\n-- tables\r\nINSERT INTO #table_options\r\nEXEC sys.sp_MSforeachdb N' \r\n\tUSE [?]; \r\n\tSELECT [db_name] = DB_NAME(), \r\n\t\tfn.name,\r\n\t\tfn.uses_ansi_nulls\r\n\tFROM sys.tables t\r\n\tCROSS APPLY (\r\n\t\tSELECT [name] = SCHEMA_NAME(t.schema_id) + ''.'' + t.name,\r\n\t\tuses_ansi_nulls = CASE WHEN t.uses_ansi_nulls = 0 THEN ''X'' ELSE '''' END \r\n\t) fn\r\n\tWHERE DB_ID() > 4 AND t.uses_ansi_nulls = 0\r\n'\r\nSELECT * FROM #table_options [to] ORDER BY [to].db_name, [to].table_name\r\n\r\nSELECT 'STORED PROCEDURES' AS 'container' \r\n-- procs \r\nIF OBJECT_ID('tempdb..#proc_options ') IS NOT NULL BEGIN \r\n\tDROP TABLE #proc_options \r\nEND\r\n\r\nCREATE TABLE #proc_options (\r\n\t[db_name] sysname,\r\n\t[proc_name] sysname,\r\n\tuses_ansi_nulls CHAR(1),\r\n\tuses_quoted_identifier CHAR(1)\r\n)\r\n-- tables\r\nINSERT INTO #proc_options \r\nEXEC sys.sp_MSforeachdb N' \r\n\tUSE [?]; \r\n\tSELECT [db_name] = DB_NAME(), \r\n\t\tn.name, \r\n\t\tCASE WHEN m.uses_ansi_nulls = 0 THEN ''X'' ELSE '''' END AS ansi_nulls, \r\n\t\tCASE WHEN m.uses_quoted_identifier = 0 THEN ''X'' ELSE '''' END AS quoted_identifier\r\n\tFROM sys.sql_modules m\r\n\tCROSS APPLY (\r\n\t\tSELECT COALESCE(\r\n\t\t\tOBJECT_SCHEMA_NAME(m.object_id) + ''.'' + OBJECT_NAME(m.object_id),\r\n\t\t\t(SELECT name FROM sys.triggers t WHERE t.object_id = m.object_id), /* database triggers do not work with object_* functions */\r\n\t\t\tCONCAT(''**DB SCOPED ITEM ('', m.object_id, '')**'') /* not a trigger, but db scoped, will have to figure out name another way */\r\n\t\t) AS [name]\r\n\t) n\r\n\tWHERE DB_ID() > 4 \r\n\t\tAND OBJECTPROPERTY(m.object_id, ''IsMsShipped'') = 0\r\n\t\tAND n.name NOT LIKE ''dbo.dt_%''\r\n\t\tAND (uses_ansi_nulls = 0 OR m.uses_quoted_identifier = 0)\r\n'\r\nSELECT * FROM #proc_options [to] ORDER BY [to].db_name, [to].proc_name \r\n\r\nSELECT 'COLUMNS' AS 'container' \r\n-- columns\r\nIF OBJECT_ID('tempdb..#column_options ') IS NOT NULL BEGIN \r\n\tDROP TABLE #column_options \r\nEND\r\n\r\nCREATE TABLE #column_options (\r\n\t[db_name] sysname,\r\n\t[table_name] sysname,\r\n\t[column_name] sysname,\r\n\t[type_name] sysname,\r\n\t[ansi_padded] CHAR(1)\r\n)\r\n-- tables\r\nINSERT INTO #column_options \r\nEXEC sys.sp_MSforeachdb N' \r\n\tUSE [?]; \r\n\tSELECT [db_name] = DB_NAME(), \r\n\t\t[table_name] = OBJECT_SCHEMA_NAME(t.object_id) + ''.'' + t.[name],\r\n\t\t[column_name] = c.[name],\r\n\t\t[data_type] = typ.[name],\r\n\t\t[ansi_padded] = ''X'' \r\n\tFROM [sys].[columns] AS [c]\r\n\t\tINNER JOIN [sys].[tables] AS [t] ON [c].object_id = [t].object_id\r\n\t\tINNER JOIN [sys].[types] AS [typ] ON [c].[system_type_id] = [typ].[system_type_id]\r\n\t\tAND [c].[user_type_id] = [typ].[user_type_id]\r\n\tWHERE DB_ID() > 4 \r\n\t\tAND OBJECTPROPERTY(t.object_id, ''IsMsShipped'') = 0\r\n\t\tAND [t].[type] = N''U''\r\n\t\tAND [c].[is_ansi_padded] = 0\r\n\t\tAND ([typ].[name] LIKE ''%char'' OR [typ].[name] LIKE ''%binary'');\r\n'\r\nSELECT * FROM #column_options [to] ORDER BY [to].db_name, [to].table_name, [to].column_name "
}
{
"id": "5230a7c5-29c4-498e-8668-0cdae9876dc0",
"prefix": "TDC_Admin_RefreshAllSqlModules",
"description": "",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9846853Z",
"permissions": [],
"body": "SET NOCOUNT ON\r\n\r\nDECLARE @sql NVARCHAR(MAX), \r\n @nl CHAR(1) = CHAR(10),\r\n @tab CHAR(1) = CHAR(9) \r\n\r\nSELECT @sql = CAST((\r\n SELECT 'RAISERROR(''REFRESHING ' + o.type_desc + ' ' + fn.name + ''', 0, 1) WITH NOWAIT;' + @nl \r\n + 'BEGIN TRY EXEC sys.sp_refreshsqlmodule @name = N''' + fn.name \r\n + '''; END TRY BEGIN CATCH PRINT CHAR(9) + ''ERROR: '' + ERROR_MESSAGE(); END CATCH;' + @nl + @nl\r\n FROM sys.objects o \r\n CROSS APPLY (\r\n SELECT [name] = QUOTENAME(OBJECT_SCHEMA_NAME(o.object_id)) + '.' + QUOTENAME(o.name) \r\n ) fn\r\n WHERE o.type IN ('P')\r\n OR (\r\n --cannot refresh these types if they are schema bound\r\n o.type IN ('V', 'FN', 'IF', 'TF')\r\n AND OBJECTPROPERTY(o.object_id, 'IsSchemaBound') = 0\r\n )\r\n ORDER BY o.type, \r\n fn.name\r\n FOR XML PATH ('')\r\n) AS NVARCHAR(MAX)) + @nl \r\n + 'RAISERROR(''DONE.'', 0, 1) WITH NOWAIT;'\r\n\r\n--SELECT @sql\r\nEXECUTE (@sql)"
}
{
"id": "ca5f943c-ab42-4c2e-adfd-864f7f828bd4",
"prefix": "TDC_Admin_ScriptLogins",
"description": "",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9846853Z",
"permissions": [],
"body": "\r\n-- more info: https://sqlity.net/en/2344/create-login-with-hashed-password/\r\nDECLARE @gen_auto_fix BIT = 1,\t/* IF 1 then the script to autofix the login in all the databases will be ouput */\r\n\t@drop_if_exists BIT = 0\t\t/* IF 1 then the login will be dropped if exists, else it will only be dropped if the login and sid do not match */\r\n\r\n\r\nSELECT sp.name, [create_sql] = \r\nCASE WHEN @drop_if_exists = 1 \r\n\tTHEN '' \r\n\tELSE 'IF NOT EXISTS(SELECT 1 FROM sys.server_principals sp WHERE sp.name = ''' + sp.name + ''' AND sp.sid = ' + fn.login_sid + ') BEGIN' \r\nEND + '\t\r\n\tPRINT ''********************************[' + sp.name + ']********************************'';\r\n\t-- The sid does not match, so drop it and re-create it IF the login DOES exist\r\n\tIF EXISTS(SELECT 1 FROM sys.server_principals sp WHERE sp.name = ''' + sp.name + ''') BEGIN;\r\n\t\tPRINT ''DROPPING LOGIN [' + sp.name + ']'';\r\n\t\tDROP LOGIN [' + sp.name + '];\r\n\tEND;\r\n\tPRINT ''CREATING LOGIN [' + sp.name + ']'';\r\n\tCREATE LOGIN [' + sp.name + '] \r\n\t\t\tWITH PASSWORD = ' + fn.pwd_hash + ' HASHED, \r\n\t\t\tDEFAULT_DATABASE = [' + sp.default_database_name + '], \r\n\t\t\tDEFAULT_LANGUAGE = [' + sp.default_language_name + '], \r\n\t\t\tSID = ' + fn.login_sid + ';' + \r\nCASE WHEN @drop_if_exists = 1 \r\n\tTHEN '' \r\n\tELSE '\r\nEND ELSE BEGIN\r\n\tALTER LOGIN [' + sp.name + '] \r\n\t\tWITH PASSWORD = ' + fn.pwd_hash + ' HASHED, \r\n\t\tDEFAULT_DATABASE = [' + sp.default_database_name + '], \r\n\t\tDEFAULT_LANGUAGE = [' + sp.default_language_name + '];\r\nEND' + \r\nCASE WHEN @gen_auto_fix = 0 THEN '' ELSE '\r\nPRINT ''AUTO FIXING LOGIN [' + sp.name + ']'';\r\nEXEC sys.sp_MSForeachdb N''\r\n\tUSE [?]; \r\n\tIF EXISTS (SELECT 1 FROM sys.databases d WHERE d.name = ''''?'''' AND d.is_read_only = 0) BEGIN\r\n\t\tIF EXISTS (SELECT 1 FROM sys.database_principals dp WHERE dp.name = ''''' + sp.name + ''''') BEGIN\r\n\t\t\tEXEC sys.sp_change_users_login @Action = ''''AutoFix'''', @LoginName = ''''' + sp.name + '''''\r\n\t\tEND \r\n\tEND\r\n''' END \r\nEND\r\nFROM sys.server_principals sp \r\nCROSS APPLY (\r\n\tSELECT login_sid = CONVERT(NVARCHAR(4000), sp.sid, 1),\r\n\t\tpwd_hash = CONVERT(NVARCHAR(4000), LOGINPROPERTY(sp.name,'PASSWORDHASH'), 1)\r\n) fn\r\nWHERE type = 'S' \r\n\tAND sp.is_disabled = 0\r\n\tAND sp.name NOT IN ('sa')\r\nORDER BY sp.name\r\n"
}
{
"id": "56976b7a-32ed-4bff-9cb9-732f3933adb4",
"prefix": "TDC_Admin_TempDBUsage",
"description": "",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9856854Z",
"permissions": [],
"body": "-- https://blog.sqlauthority.com/2015/01/23/sql-server-who-is-consuming-my-tempdb-now/\r\n\r\nSELECT st.dbid AS QueryExecutionContextDBID,\r\n DB_NAME(st.dbid) AS QueryExecContextDBNAME,\r\n st.objectid AS ModuleObjectId,\r\n SUBSTRING( st.text,\r\n dmv_er.statement_start_offset / 2 + 1,\r\n (CASE\r\n WHEN dmv_er.statement_end_offset = -1 THEN\r\n LEN(CONVERT(NVARCHAR(MAX), st.text)) * 2\r\n ELSE\r\n dmv_er.statement_end_offset\r\n END - dmv_er.statement_start_offset\r\n ) / 2\r\n ) AS Query_Text,\r\n dmv_tsu.session_id,\r\n dmv_tsu.request_id,\r\n dmv_tsu.exec_context_id,\r\n (dmv_tsu.user_objects_alloc_page_count - dmv_tsu.user_objects_dealloc_page_count) AS OutStanding_user_objects_page_counts,\r\n (dmv_tsu.internal_objects_alloc_page_count - dmv_tsu.internal_objects_dealloc_page_count) AS OutStanding_internal_objects_page_counts,\r\n dmv_er.start_time,\r\n dmv_er.command,\r\n dmv_er.open_transaction_count,\r\n dmv_er.percent_complete,\r\n dmv_er.estimated_completion_time,\r\n dmv_er.cpu_time,\r\n dmv_er.total_elapsed_time,\r\n dmv_er.reads,\r\n dmv_er.writes,\r\n dmv_er.logical_reads,\r\n dmv_er.granted_query_memory,\r\n dmv_es.host_name,\r\n dmv_es.login_name,\r\n dmv_es.program_name\r\nFROM sys.dm_db_task_space_usage dmv_tsu\r\nINNER JOIN sys.dm_exec_requests dmv_er\r\n ON (\r\n dmv_tsu.session_id = dmv_er.session_id\r\n AND dmv_tsu.request_id = dmv_er.request_id\r\n )\r\nINNER JOIN sys.dm_exec_sessions dmv_es\r\n ON (dmv_tsu.session_id = dmv_es.session_id)\r\nCROSS APPLY sys.dm_exec_sql_text(dmv_er.sql_handle) st\r\nWHERE (dmv_tsu.internal_objects_alloc_page_count + dmv_tsu.user_objects_alloc_page_count) > 0\r\nORDER BY (dmv_tsu.user_objects_alloc_page_count - dmv_tsu.user_objects_dealloc_page_count)\r\n + (dmv_tsu.internal_objects_alloc_page_count - dmv_tsu.internal_objects_dealloc_page_count) DESC;\r\n\r\n"
}
{
"id": "02f7d85b-b4c5-44a6-a935-ae93028847cd",
"prefix": "TDC_AlterAllFileGrowths",
"description": "",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9856854Z",
"permissions": [],
"body": "EXEC sys.sp_MSforeachdb @command1 = N'\r\n\tUSE [?]\r\n\tIF DB_NAME() IN (''master'', ''tempdb'', ''msdb'') RETURN\r\n\r\n\tDECLARE @sql VARCHAR(MAX) = CONCAT(''USE [master]'', CHAR(10), ''GO'', CHAR(10))\r\n\r\n\tSELECT @sql += CAST((\r\n\t\tSELECT CASE \r\n\t\t\tWHEN type_desc = ''ROWS'' \r\n\t\t\t\tTHEN CONCAT(''ALTER DATABASE ['', DB_NAME(), ''] MODIFY FILE ( NAME = N'''''', df.name, '''''', FILEGROWTH = 512MB );'', CHAR(10)) \r\n\t\t\tELSE \r\n\t\t\t\tCONCAT(''ALTER DATABASE ['', DB_NAME(), ''] MODIFY FILE ( NAME = N'''''', df.name, '''''', FILEGROWTH = 512MB );'', CHAR(10)) \r\n\t\t\tEND\r\n\t\tFROM sys.database_files df\r\n\t\tFOR XML PATH('''')\r\n\t) AS VARCHAR(8000))\r\n\r\n\tPRINT @sql\r\n\t--EXEC (@sql)\r\n'"
}
{
"id": "be5fb3ae-591d-48af-98b7-c1f5a976cfa9",
"prefix": "TDC_AlterColumn",
"description": "Alter Column If Exists",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9856854Z",
"permissions": [],
"body": "IF EXISTS (SELECT 1 FROM sys.columns WHERE object_id = OBJECT_ID(N'$schema_name$.$table_name$') AND name = N'$column_name$')\r\n\tALTER TABLE $schema_name$.$table_name$ ALTER COLUMN $column_name$ $datatype$;\r\nGO\r\n$CURSOR$",
"placeholders": [
{
"name": "schema_name",
"defaultValue": null
},
{
"name": "table_name",
"defaultValue": null
},
{
"name": "column_name",
"defaultValue": null
},
{
"name": "datatype",
"defaultValue": null
}
]
}
{
"id": "59c08bf3-42f3-4541-8da7-370d4fd5aead",
"prefix": "TDC_AlterFileSize",
"description": "Alter Database File Size and Growth",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9856854Z",
"permissions": [],
"body": "USE master;\r\nGO\r\n\r\nALTER DATABASE [$DatabaseName$]\r\nMODIFY FILE (\r\n\t\t\t\tNAME = N'$LogicalFileName$',\r\n\t\t\t\tSIZE = $current_size$ KB, --{ current_size [ KB | MB | GB | TB ] }\r\n\t\t\t\tMAXSIZE = $max_size$ KB, --{ max_size [ KB | MB | GB | TB ] | UNLIMITED } \r\n\t\t\t\tFILEGROWTH = $growth_increment$ KB --{ growth_increment [ KB | MB | GB | TB ] | % } \r\n\t\t\t);\r\nGO",
"placeholders": [
{
"name": "DatabaseName",
"defaultValue": null
},
{
"name": "current_size",
"defaultValue": null
},
{
"name": "max_size",
"defaultValue": null
},
{
"name": "growth_increment",
"defaultValue": null
},
{
"name": "LogicalFileName",
"defaultValue": null
}
]
}
{
"id": "876a0ab6-e28e-44e4-9028-3820a57eaa45",
"prefix": "TDC_CaptureWaitStatsForSingleSPID",
"description": "To Create WaitStats XEvent Session and Analyse the XEvent Session from XEL and XEM files Created",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9866855Z",
"permissions": [],
"body": "/* =========================================================================================================================================\r\n-- Server\t\t: LOCAL SERVER\r\n-- Database\t\t: master\r\n-- Script\t\t: CaptureWaitStatsForSingleSPID\r\n-- Description\t: To Create WaitStats XEvent Session and Analyse the XEvent Session from XEL and XEM files Created\r\n-- Link\t\t\t: https://www.sqlskills.com/blogs/paul/capturing-wait-stats-for-a-single-operation/\r\n-- Usage\t\t: Open New Query Window and Get The SPID(number) of the Query you wanted to Execute\r\n--\t\t\t\t\tCreate a XEvent for the SPID($SPID$) to Monitor the WaitStats\r\n-- **\tFOLLOW the Below Steps Sequentially To Create XEvent and Analyse the XEvent Session\r\n========================================================================================================================================= */\r\nUSE master;\r\nGO\r\n--\r\n/* ===== ** CREATE XEvent Session ** ==================================================================================================== */\r\n--$BeginRegion: STEP 1: CREATE Folder XEvents to Collect XEL and XEM Files\r\nEXEC sys.xp_cmdshell 'mkdir \"C:\\SQL\\XEvents\"';\r\nGO \r\n--$EndRegion: STEP 1: CREATE Folder XEvents to Collect XEL and XEM Files\r\n--\r\n--$BeginRegion: STEP 2: DROP and CREATE the WaitStats XEvent Session If Exists\r\nIF EXISTS (SELECT * FROM sys.server_event_sessions WHERE name = 'MonitorWaitsForSPID$SPID$')\r\n DROP EVENT SESSION MonitorWaitsForSPID$SPID$ ON SERVER\r\nGO\r\n--\r\nCREATE EVENT SESSION MonitorWaitsForSPID$SPID$\r\nON SERVER\r\n\tADD EVENT sqlos.wait_info\r\n\t(WHERE sqlserver.session_id = $SPID$ /* session_id of connection to monitor */)\r\n\tADD TARGET package0.asynchronous_file_target\r\n\t(SET FILENAME = N'C:\\SQL\\XEvents\\EE_WaitStatsForSPID$SPID$.xel', METADATAFILE = N'C:\\SQL\\XEvents\\EE_WaitStatsForSPID$SPID$.xem')\r\nWITH (MAX_DISPATCH_LATENCY = 1 SECONDS);\r\nGO\r\n--$EndRegion: STEP 2: DROP and CREATE the WaitStats XEvent Session If Exists\r\n--\r\n--\r\n/* ===== ** START XEvent Session >> EXECUTE SPID >> STOP XEvent Session ** ============================================================== */\r\n--$BeginRegion: STEP 3: START the XEvent Session\r\nALTER EVENT SESSION MonitorWaitsForSPID$SPID$ ON SERVER STATE = START;\r\nGO\r\n--$EndRegion: STEP 3: START the XEvent Session\r\n--\r\n--$BeginRegion: STEP 4: RUN THE QUERY in SPID $SPID$\r\n--** DO THE QUERY **--\r\n--$EndRegion: STEP 4: RUN THE QUERY in SPID $SPID$\r\n--\r\n--$BeginRegion: STEP 5: STOP the XEvent Session\r\nALTER EVENT SESSION MonitorWaitsForSPID$SPID$ ON SERVER STATE = STOP;\r\nGO\r\n--$EndRegion: STEP 5: STOP the XEvent Session\r\n--\r\n--\r\n/* ===== ** ANALYSE THE XEvent Session CAPTURED ** ====================================================================================== */\r\n--$BeginRegion: STEP 6: ANALYSE the WaitStats XEvent Session\r\nIF OBJECT_ID('tempdb..#RawEventData') IS NOT NULL\r\n\tDROP TABLE #RawEventData;\r\nGO\r\nCREATE TABLE #RawEventData\r\n(\r\n\tRowID INT IDENTITY PRIMARY KEY,\r\n\tEvent_Data XML\r\n);\r\nGO\r\nINSERT INTO #RawEventData ( Event_Data)\r\nSELECT CAST(event_data AS XML) AS \"Event_Data\"\r\nFROM sys.fn_xe_file_target_read_file('C:\\SQL\\XEvents\\EE_WaitStatsForSPID$SPID$*.xel', 'C:\\SQL\\XEvents\\EE_WaitStatsForSPID$SPID$*.xem', NULL, NULL);\r\nGO\r\nSELECT waits.[Wait Type],\r\n\t COUNT(*) AS \"Wait Count\",\r\n\t SUM(waits.Duration) AS \"Total Wait Time (ms)\",\r\n\t SUM(waits.Duration) - SUM(waits.[Signal Duration]) AS \"Total Resource Wait Time (ms)\",\r\n\t SUM(waits.[Signal Duration]) AS \"Total Signal Wait Time (ms)\"\r\nFROM (\r\n\t\t SELECT Event_Data.value('(/event/@timestamp)[1]', 'DATETIME') AS \"Time\",\r\n\t\t\t\tEvent_Data.value('(/event/data[@name=''wait_type'']/text)[1]', 'VARCHAR(100)') AS \"Wait Type\",\r\n\t\t\t\tEvent_Data.value('(/event/data[@name=''opcode'']/text)[1]', 'VARCHAR(100)') AS \"Op\",\r\n\t\t\t\tEvent_Data.value('(/event/data[@name=''duration'']/value)[1]', 'BIGINT') AS \"Duration\",\r\n\t\t\t\tEvent_Data.value('(/event/data[@name=''signal_duration'']/value)[1]', 'BIGINT') AS \"Signal Duration\"\r\n\t\t FROM #RawEventData\r\n\t ) AS waits\r\nWHERE waits.Op = 'End'\r\nGROUP BY waits.[Wait Type]\r\nORDER BY [Total Wait Time (ms)] DESC;\r\nGO\r\n--$EndRegion: STEP 6: ANALYSE the WaitStats XEvent Session",
"placeholders": [
{
"name": "SPID",
"defaultValue": null
}
]
}
{
"id": "fbbee314-28e6-4994-8c87-d9a7c71230da",
"prefix": "TDC_Comment",
"description": "Script Comment",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9866855Z",
"permissions": [],
"body": "/* =========================================================================================================================================\n-- Author\t\t: $USER$\n-- Create Date\t: $DATE$ $TIME$\n-- Server\t\t: $SERVER$\n-- Database\t\t: $DBNAME$\n-- Script\t\t: $ScriptName$\n-- Description\t:\n-- Usage\t\t:\n-- History\t\t:\n========================================================================================================================================= */\n$CURSOR$",
"placeholders": [
{
"name": "ScriptName",
"defaultValue": ""
}
]
}
{
"id": "94508c0b-1fed-4e17-8102-7d65cad501e3",
"prefix": "TDC_CommentToNotChangeCode",
"description": "Do Not Change Code Comment",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9866855Z",
"permissions": [],
"body": "/* ===== ** DO NOT CHANGE CODE BELOW FROM HERE ** =========================================================================================================== */"
}
{
"id": "60d4ed64-ebe1-477e-9d98-9c7d43ae71e4",
"prefix": "TDC_ConcatString",
"description": "Concatenate Column Values Into a Comma Separated String (STUFF-CSV)",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9866855Z",
"permissions": [],
"body": "SELECT STUFF(\n\t\t\t\t((SELECT ', ' + $table_alias$.$column_name$\n\t\t\t\tFROM $schema_name$.$table_name$ AS $table_alias$\n\t\t\t\tFOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)')), -- CSV Expression will Append to Initial Expression\n\t\t\t\t1, -- Initial Expression Start Position\n\t\t\t\t2, -- Replacement Length\n\t\t\t\t'' -- Initial Expression\n\t\t\t) AS $column_alias$",
"placeholders": [
{
"name": "table_alias",
"defaultValue": "T"
},
{
"name": "column_name",
"defaultValue": ""
},
{
"name": "schema_name",
"defaultValue": "dbo"
},
{
"name": "table_name",
"defaultValue": ""
},
{
"name": "column_alias",
"defaultValue": ""
}
]
}
{
"id": "977fde7a-f428-4baf-b23f-e13a3da14670",
"prefix": "TDC_Constraint_CheckData",
"description": "",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9876854Z",
"permissions": [],
"body": "/*\r\n TIM C: \r\n Purpose: To check the check and foreign keys that are disabled or not trusted of all user databases or a single db for invalid data in tables by \r\n using DBCC CHECKCONSTRAINTS, and generate the cleanup scripts, and the scripts to re-enable all constraints. \r\n Will also try to re-enable untrusted constraints. \r\n NOTE: Change the @current_db_only variable to run either just the current db, or all dbs\r\n*/\r\nDECLARE @current_db_only BIT = 1,\r\n @db_id VARCHAR(20) = NULL\r\n\r\nIF @current_db_only = 1 SET @db_id = DB_ID()\r\n\r\nSET NOCOUNT ON \r\nIF OBJECT_ID('tempdb..#ConstraintIssues') IS NOT NULL BEGIN \r\n DROP TABLE #ConstraintIssues \r\nEND\r\nCREATE TABLE #ConstraintIssues(\r\n [Database] sysname NULL DEFAULT (QUOTENAME(DB_NAME())), \r\n [Table] sysname NOT NULL, \r\n [Constraint] sysname NOT NULL, \r\n [Violation] VARCHAR(2000) NULL\r\n);\r\n\r\nDECLARE @foreach_sql NVARCHAR(2000) = N' \r\nUSE [?];\r\nIF DB_ID() <= 4 RETURN;\r\nDECLARE @db_id INT = ' + ISNULL(@db_id, 'NULL') + '\r\nIF @db_id IS NOT NULL AND @db_id <> DB_ID() RETURN;\r\n \r\nDECLARE @msg VARCHAR(1000) = CONCAT(''QUERYING: '', DB_NAME())\r\nRAISERROR (@msg, 0, 1) WITH NOWAIT\r\nDECLARE @sql NVARCHAR(max) = REPLACE((\r\n SELECT CONCAT(''INSERT INTO #ConstraintIssues ([Table], [Constraint], Violation) EXEC (''''DBCC CHECKCONSTRAINTS ('''''''''', \r\n CONCAT(QUOTENAME(SCHEMA_NAME(c.schema_id)), ''.'', QUOTENAME(c.name)), '''''''''') WITH NO_INFOMSGS'''');##CRLF##'') \r\n FROM (\r\n SELECT name, ck.schema_id, ck.parent_object_id\r\n FROM sys.check_constraints ck\r\n WHERE ck.is_disabled = 1 \r\n OR ck.is_not_trusted = 1\r\n UNION ALL \r\n SELECT name, fk.schema_id, fk.parent_object_id\r\n FROM sys.foreign_keys fk\r\n WHERE fk.is_disabled = 1 \r\n OR fk.is_not_trusted = 1\r\n ) c\r\n FOR XML PATH('''')\r\n), ''##CRLF##'', CONCAT(CHAR(13), CHAR(10)))\r\nIF LEN(@sql) > 0 BEGIN \r\n --PRINT @sql\r\n EXEC (@sql)\r\nEND\r\nINSERT INTO #ConstraintIssues ([Table], [Constraint])\r\nSELECT c.[table],\r\n c.[constraint]\r\nFROM (\r\n SELECT [table] = CONCAT(QUOTENAME(OBJECT_SCHEMA_NAME(ck.parent_object_id)), ''.'', QUOTENAME(OBJECT_NAME(ck.parent_object_id))),\r\n [constraint] = QUOTENAME(ck.name) COLLATE SQL_Latin1_General_CP1_CI_AS\r\n FROM sys.check_constraints ck\r\n WHERE ck.is_disabled = 1 \r\n OR ck.is_not_trusted = 1\r\n UNION ALL \r\n SELECT [table] = CONCAT(QUOTENAME(OBJECT_SCHEMA_NAME(fk.parent_object_id)), ''.'', QUOTENAME(OBJECT_NAME(fk.parent_object_id))),\r\n [constraint] = QUOTENAME(fk.name) COLLATE SQL_Latin1_General_CP1_CI_AS\r\n FROM sys.foreign_keys fk\r\n WHERE fk.is_disabled = 1 \r\n OR fk.is_not_trusted = 1\r\n) c LEFT JOIN #ConstraintIssues ci \r\nON ci.[Table] = c.[table] \r\n AND ci.[Constraint] = c.[constraint]\r\nWHERE ci.[Database] IS NULL \r\n AND ci.[Table] IS NULL\r\n AND ci.[Constraint] IS NULL'\r\n\r\n\r\n--SELECT LEN (@foreach_sql), @foreach_sql\r\nEXEC sys.sp_MSforeachdb @command1 = @foreach_sql \r\n\r\nSELECT [Database],\r\n [Table],\r\n [Constraint],\r\n [Violation] \r\nFROM #ConstraintIssues\r\nORDER BY [Database], \r\n [Table], \r\n [Constraint]\r\n\r\nIF EXISTS (SELECT 1 FROM #ConstraintIssues) BEGIN\r\n DECLARE @cleanup_sql NVARCHAR(MAX) = REPLACE((\r\n SELECT CONCAT('DELETE FROM ', ci.[Database], '.', ci.[Table], ' WHERE ', ci.Violation, ';##CRLF##') \r\n FROM #ConstraintIssues ci\r\n WHERE ci.Violation IS NOT NULL\r\n ORDER BY ci.[Database], \r\n ci.[Table], \r\n ci.[Constraint]\r\n FOR XML PATH('')\r\n ), '##CRLF##', CONCAT(CHAR(13), CHAR(10)))\r\n \r\n DECLARE @enable_fk_sql NVARCHAR(MAX) = REPLACE((\r\n SELECT CONCAT('ALTER TABLE ', ci.[Database], '.', ci.[Table], ' WITH CHECK CHECK CONSTRAINT ', ci.[Constraint], ';##CRLF##') \r\n FROM #ConstraintIssues ci\r\n GROUP BY ci.[Database], \r\n ci.[Table], \r\n ci.[Constraint]\r\n ORDER BY ci.[Database], \r\n ci.[Table], \r\n ci.[Constraint]\r\n FOR XML PATH('')\r\n ), '##CRLF##', CONCAT(CHAR(13), CHAR(10)))\r\n\r\n -- to copy/paste out may need to turn this on: https://blog.sqlauthority.com/2016/06/03/sql-server-maintain-carriage-return-enter-key-ssms-2016-copy-paste/\r\n SELECT @cleanup_sql AS [cleanup_sql], \r\n @enable_fk_sql AS [enable_fk_sql]\r\n \r\n BEGIN TRAN\r\n BEGIN TRY\r\n -- run the cleanup and enable?\r\n --IF LEN(@cleanup_sql) > 0 EXEC(@cleanup_sql)\r\n --IF LEN(@enable_fk_sql) > 0 EXEC(@enable_fk_sql)\r\n COMMIT TRAN\r\n END TRY\r\n BEGIN CATCH\r\n ROLLBACK TRAN\r\n ;THROW;\r\n END CATCH\r\nEND\r\n"
}
{
"id": "ab12850b-cf73-4316-898f-f8996764d472",
"prefix": "TDC_Constraint_FindUntrusted",
"description": "",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9876854Z",
"permissions": [],
"body": "-- https://www.brentozar.com/blitz/foreign-key-trusted/\r\n\r\nSELECT '[' + s.name + '].[' + o.name + '].[' + i.name + ']' AS keyname\r\nfrom sys.foreign_keys i\r\nINNER JOIN sys.objects o ON i.parent_object_id = o.object_id\r\nINNER JOIN sys.schemas s ON o.schema_id = s.schema_id\r\nWHERE i.is_not_trusted = 1 AND i.is_not_for_replication = 0;\r\nGO\r\n\r\nSELECT '[' + s.name + '].[' + o.name + '].[' + i.name + ']' AS keyname\r\nfrom sys.check_constraints i\r\nINNER JOIN sys.objects o ON i.parent_object_id = o.object_id\r\nINNER JOIN sys.schemas s ON o.schema_id = s.schema_id\r\nWHERE i.is_not_trusted = 1 AND i.is_not_for_replication = 0 AND i.is_disabled = 0;\r\nGO"
}
{
"id": "6f41c9e2-a3e1-46d5-a4a7-1b525deeb568",
"prefix": "TDC_Constraint_FindUsingFunctions",
"description": "",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9876854Z",
"permissions": [],
"body": "IF OBJECT_ID('tempdb..#constraints_with_functions') IS NOT NULL BEGIN \r\n\tDROP TABLE #constraints_with_functions \r\nEND\r\nGO\r\nCREATE TABLE [#constraints_with_functions](\r\n\t[database_name] sysname NOT NULL,\r\n\t[constraint_name] [sysname] NOT NULL,\r\n\t[definition] [nvarchar](max) NULL,\r\n\t[object_name] [sysname] NOT NULL,\r\n\t[object_id] [int] NOT NULL,\r\n\t[principal_id] [int] NULL,\r\n\t[schema_id] [int] NOT NULL,\r\n\t[parent_object_id] [int] NOT NULL,\r\n\t[type] [char](2) NOT NULL,\r\n\t[type_desc] [nvarchar](60) NULL,\r\n\t[create_date] [datetime] NOT NULL,\r\n\t[modify_date] [datetime] NOT NULL,\r\n\t[is_ms_shipped] [bit] NOT NULL,\r\n\t[is_published] [bit] NOT NULL,\r\n\t[is_schema_published] [bit] NOT NULL\r\n) \r\nGO\r\n\r\nSET NOCOUNT ON\r\n\r\nEXEC sp_msforeachdb @command1 = N'\r\n\tIF DB_ID(''?'') <= 4 RETURN\r\n\tRAISERROR (''Scanning: [?]'', 0, 1) WITH NOWAIT\r\n\tUSE [?];\r\n\t\r\n\tIF HAS_DBACCESS(''?'') = 0 BEGIN\r\n\t\tRAISERROR (''NO DATABASE ACCESS FOR [?]'', 0, 1) WITH NOWAIT\r\n\t\tRETURN\r\n\tEND\r\n\tIF HAS_PERMS_BY_NAME(DB_NAME(), ''DATABASE'', ''VIEW DATABASE STATE'') = 0 BEGIN\r\n\t\tRAISERROR (''MISSING \"VIEW DATABASE STATE\" PERMISSION FOR DB [?]'', 0, 1) WITH NOWAIT\r\n\t\tRETURN\r\n\tEND\r\n\t;WITH c1 AS (\r\n\t\tSELECT name, definition\r\n\t\tFROM sys.check_constraints\r\n\t\tUNION ALL\r\n\t\tSELECT name, definition\r\n\t\tFROM sys.default_constraints\r\n\t)\r\n\tINSERT INTO #constraints_with_functions (\r\n\t\tdatabase_name,\r\n\t\tconstraint_name,\r\n\t\tdefinition,\r\n\t\tobject_name,\r\n\t\tobject_id,\r\n\t\tprincipal_id,\r\n\t\tschema_id,\r\n\t\tparent_object_id,\r\n\t\ttype,\r\n\t\ttype_desc,\r\n\t\tcreate_date,\r\n\t\tmodify_date,\r\n\t\tis_ms_shipped,\r\n\t\tis_published,\r\n\t\tis_schema_published\r\n\t)\r\n\tSELECT database_name = DB_NAME(),\r\n\t\t [constraint_name] = c1.name,\r\n\t\t c1.definition,\r\n\t\t [object_name] = o.name,\r\n\t\t o.object_id,\r\n\t\t o.principal_id,\r\n\t\t o.schema_id,\r\n\t\t o.parent_object_id,\r\n\t\t o.type,\r\n\t\t o.type_desc,\r\n\t\t o.create_date,\r\n\t\t o.modify_date,\r\n\t\t o.is_ms_shipped,\r\n\t\t o.is_published,\r\n\t\t o.is_schema_published\r\n\tFROM c1, sys.objects AS o\r\n\tWHERE o.type IN ( ''FN'', ''TF'' )\r\n\tAND (\r\n\t\t-- eliminate false positives by ensuring the definition has a period before the function name\r\n\t\tc1.definition LIKE ''%.'' + o.name + ''%'' \r\n\t\tOR c1.definition LIKE ''%.\\['' + o.name + ''%'' ESCAPE ''\\''\r\n\t);'\r\n\r\n\r\nSELECT * FROM #constraints_with_functions"
}
{
"id": "3d862266-d057-4c04-9cba-325bedee9dff",
"prefix": "TDC_Constraint_RenameAll",
"description": "",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9886854Z",
"permissions": [],
"body": "-- Purpose: Rename all constraints OR auto named constraints\r\nDECLARE @printonly bit = 1 -- change this line to either just print the results (1), or to exec them (0)\r\n\t, @renameAll bit = 1 -- change this to rename all constraints(1), or just auto named (0)\r\n\r\nSET NOCOUNT ON;\r\n\r\nIF OBJECT_ID('tempdb..#contraints') IS NOT NULL BEGIN\r\n DROP TABLE #contraints;\r\nEND\r\n\r\nDECLARE @sql varchar(MAX) = ''\r\n\t, @rowCount int = 50 -- how many renames to do at a time\r\n\t, @currentCount int = 0\r\n\r\nCREATE TABLE #contraints (\r\n\t[RowId] int NOT NULL IDENTITY(1,1) PRIMARY KEY,\r\n\t[ConstraintRowId] int NOT NULL,\r\n\t[SchemaName] sysname not null,\r\n\t[ConstraintName] sysname not null,\r\n\t[TableName] sysname not null,\r\n\t[ColumnName] sysname null,\r\n\t[RemoteTableName] sysname null,\r\n\t[type] varchar(10) not null,\r\n\t[NewConstraintName] varchar(2048) null\r\n);\r\n\r\n--foreign keys\r\nINSERT INTO #contraints ([ConstraintRowId], [SchemaName], [ConstraintName], [TableName], [ColumnName], [RemoteTableName], [type])\r\nSELECT ROW_NUMBER() OVER (PARTITION BY fk.[object_id], fk.[referenced_object_id] ORDER BY OBJECT_NAME(fk.[referenced_object_id])),\r\n\t[SchemaName] = SCHEMA_NAME(fk.[schema_id]), \r\n\t[ConstraintName] = fk.[name], \r\n\t[TableName] = OBJECT_NAME(fk.[parent_object_id]), \r\n\t[ColumnName] = NULL,\r\n\t[RemoteTableName] = OBJECT_NAME(fk.[referenced_object_id]),\r\n\to.type \r\nFROM sys.[foreign_keys] fk\r\nINNER JOIN sys.[objects] o ON fk.[object_id] = o.[object_id]\r\n\r\n--unique constraints\r\nINSERT INTO #contraints ([ConstraintRowId], [SchemaName], [ConstraintName], [TableName], [ColumnName], [RemoteTableName], [type])\r\nSELECT ROW_NUMBER() OVER (PARTITION BY kc.[object_id] ORDER BY kc.[object_id]),\r\n\t[SchemaName] = SCHEMA_NAME(kc.[schema_id]), \r\n\t[ConstraintName] = kc.[name], \r\n\t[TableName] = OBJECT_NAME(kc.[parent_object_id]), \r\n\t[ColumnName] = NULL,\r\n\t[RemoteTableName] = NULL,\r\n\to.type\r\nFROM sys.[key_constraints] kc\r\nINNER JOIN sys.[objects] o ON kc.[object_id] = o.[object_id]\r\nWHERE kc.[type] = 'UQ'\r\n\tAND OBJECTPROPERTYEX(kc.[parent_object_id], 'BaseType') <> 'TT' -- ignore table types as their constraints cannot be named\r\n\r\n-- all other constraints\r\nINSERT INTO #contraints ([ConstraintRowId], [SchemaName], [ConstraintName], [TableName], [ColumnName], [RemoteTableName], [type])\r\nSELECT ROW_NUMBER() OVER (PARTITION BY s.[id], o.type ORDER BY s.[constid]),\r\n\t[SchemaName] = SCHEMA_NAME(o.[schema_id]), \r\n\t[ConstraintName] = o.[name], \r\n\t[TableName] = OBJECT_NAME(s.[id]), \r\n\t[ColumnName] = COL_NAME(s.[id], s.[colid]),\r\n\t[RemoteTableName] = NULL,\r\n\to.type\r\nFROM sys.[sysconstraints] s\r\nINNER JOIN sys.[objects] o ON s.[constid] = o.[object_id]\r\nWHERE o.type NOT IN ('F', 'UQ')\r\n\tAND OBJECTPROPERTYEX(s.[id], 'BaseType') <> 'TT' -- ignore table types as their constraints cannot be named\r\nORDER BY o.[object_id], s.[constid]\r\n\r\n\r\nDELETE FROM [#contraints] \r\nWHERE CASE \r\n\t\tWHEN @renameAll = 0 AND [ConstraintName] LIKE '[A-Z][A-Z][_][_]%' THEN 0\r\n\t\tWHEN @renameAll = 1 THEN 0\r\n\t\tELSE 1\r\n\tEND = 1\r\n\tOR CASE --delete constraints that already match the desired pattern\r\n\t\tWHEN [type] = 'PK' AND [ConstraintName] LIKE 'PK[_]' + [TableName] THEN 1\r\n\t\tWHEN [type] = 'D' AND [ConstraintName] LIKE 'DF[_]' + [TableName] + '[_]' + [ColumnName] THEN 1\r\n\t\t--WHEN [type] = 'D' AND [ConstraintName] LIKE 'DF[0-9][0-9][_]' + [TableName] THEN 1\r\n\t\tWHEN [type] = 'F' AND [ConstraintName] LIKE 'FK[0-9][0-9][_]' + [TableName] + '_' + [RemoteTableName] THEN 1\r\n\t\tWHEN [type] = 'C' AND [ConstraintName] LIKE 'CK[0-9][0-9][_]' + [TableName] THEN 1\r\n\t\tWHEN [type] = 'UQ' AND [ConstraintName] LIKE 'UQ[0-9][0-9][_]' + [TableName] THEN 1\r\n\t\tELSE 0\r\n\tEND = 1;\r\n\r\nUPDATE c\r\n\tSET c.[NewConstraintName] = fnc.[NewConstraintName]\r\nFROM [#contraints] c\r\nCROSS APPLY (\r\n\tSELECT CID = RIGHT('0' + CAST(c.[ConstraintRowId] AS varchar(16)), 2) + '_'\r\n) fn\r\nCROSS APPLY (\r\n\tSELECT NewConstraintName = CASE c.[type]\r\n\t\tWHEN 'PK' THEN 'PK_' + c.[TableName] -- PK = PRIMARY KEY constraint\r\n\t\tWHEN 'D' THEN 'DF_' + c.[TableName] + '_' + c.[ColumnName] -- D = DEFAULT (constraint or stand-alone)\r\n\t\t--WHEN 'D' THEN 'DF' + fn.CID + c.[TableName] -- D = DEFAULT (constraint or stand-alone)\r\n\t\tWHEN 'F' THEN 'FK' + fn.CID + c.[TableName] + '_' + c.[RemoteTableName] -- F = FOREIGN KEY constraint\r\n\t\tWHEN 'C' THEN 'CK' + fn.CID + c.[TableName] -- C = CHECK constraint\r\n\t\tWHEN 'UQ' THEN 'UQ' + fn.CID + c.[TableName] -- UQ = UNIQUE constraint\r\n\t\tELSE '-- Unknown Constraint Type: ' + c.[type] + ' - ' + c.[ConstraintName] + CHAR(10)\r\n\tEND \r\n) fnc\r\n\r\n--SELECT * FROM [#contraints] c\r\n\r\nIF EXISTS (SELECT 1 FROM [#contraints] c WHERE LEN(c.[NewConstraintName]) = 0) BEGIN\r\n\tPRINT 'A NULL NewConstraintName was found. Please check the data, and fix any issues.'\r\n\tRETURN;\r\nEND\r\n\r\nSET XACT_ABORT ON\r\nBEGIN TRAN\r\n\r\nPRINT 'SET NOEXEC OFF\r\nSET XACT_ABORT ON\r\nBEGIN TRAN'\r\n\r\nWHILE EXISTS (SELECT TOP 1 * FROM [#contraints] c) BEGIN\r\n\tSET @sql = '';\r\n\r\n\tSELECT @currentCount = COUNT(*) FROM [#contraints] c\r\n\tPRINT '--Count: ' + CAST(@currentCount AS varchar(16))\r\n\r\n\tSELECT TOP(@rowCount) @sql = @sql \r\n\t\t+ 'EXEC sp_rename N''' + c.[SchemaName] + '.' + c.[ConstraintName] \r\n\t\t+ ''', N''' + c.[NewConstraintName] + ''', ''OBJECT''; IF @@ERROR <> 0 SET NOEXEC ON;' + CHAR(10)\r\n\tFROM #contraints c\r\n\r\n\tPRINT @sql;\r\n\tIF @printonly = 0 EXEC(@sql);\r\n\tIF @@ERROR <> 0 GOTO FINISH;\r\n\t\r\n\tDELETE TOP (@rowCount) \r\n\tFROM [#contraints]\r\n\tIF @@ERROR <> 0 GOTO FINISH;\r\nEND\r\n\r\nPRINT 'COMMIT TRAN'\r\n\r\n--comment out this line for testing\r\nCOMMIT TRAN;\r\n\r\nFINISH:\r\nIF @@TRANCOUNT > 0 ROLLBACK TRAN;\r\n\r\nIF OBJECT_ID('tempdb..#contraints') IS NOT NULL BEGIN\r\n DROP TABLE #contraints;\r\nEND\r\n"
}
{
"id": "14b2e8b8-5b41-4ce3-a3fa-8b04f4e8575b",
"prefix": "TDC_Constraints_GetAllRelations",
"description": "To Get Details of All Constraints like PK, FK, UK etc",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9886854Z",
"permissions": [],
"body": "/* =========================================================================================================================================\r\n-- Script\t\t: Get_All_Constraints_And_PK_FK_Relations_Between_Tables(PK_FK_UK)\r\n-- Description\t: To Get Details of All Constraints like 'PRIMARY_KEY_CONSTRAINT', 'FOREIGN_KEY_CONSTRAINT', 'UNIQUE_CONSTRAINT'\r\n--\t\t\t\t Retrives All Complex Relations like Composite Primary Keys, Foreign Keys And Respective Columns with CASCADE.\r\n-- Server\t\t: LOCALHOST\r\n-- Database\t\t: USER Database\r\n========================================================================================================================================= */\r\nSELECT --\r\n\tCTE.CONSTRAINT_NAME,\r\n\tCTE.CONSTRAINT_TYPE,\r\n\tREPLACE(ISNULL(CTE.[ON_DELETE?], ''), 'NO_ACTION', '') AS \"ON_DELETE?\",\r\n\tREPLACE(ISNULL(CTE.[ON_UPDATE?], ''), 'NO_ACTION', '') AS \"ON_UPDATE?\",\r\n\tISNULL(CTE.[IS_ENABLED?], '') AS \"IS_ENABLED?\",\r\n\tISNULL(CTE.[IS_TRUSTED?], '') AS \"IS_TRUSTED?\",\r\n\t'|' AS \"||\",\r\n\tCTE.MAIN_TABLE_SCHEMA,\r\n\tCTE.MAIN_TABLE_NAME,\r\n\tCASE CTE.CONSTRAINT_TYPE\r\n\t\tWHEN 'PRIMARY_KEY_CONSTRAINT' THEN 'PK: ' + CASE WHEN (CHARINDEX(',', CTE.MAIN_TABLE_COLUMNS) > 0) THEN '( ' + CTE.MAIN_TABLE_COLUMNS + ' )' ELSE CTE.MAIN_TABLE_COLUMNS END\r\n\t\tWHEN 'FOREIGN_KEY_CONSTRAINT' THEN 'FK: ' + CASE WHEN (CHARINDEX(',', CTE.MAIN_TABLE_COLUMNS) > 0) THEN '( ' + CTE.MAIN_TABLE_COLUMNS + ' )' ELSE CTE.MAIN_TABLE_COLUMNS END\r\n\t\tWHEN 'UNIQUE_CONSTRAINT' THEN 'UK: ' + CASE WHEN (CHARINDEX(',', CTE.MAIN_TABLE_COLUMNS) > 0) THEN '( ' + CTE.MAIN_TABLE_COLUMNS + ' )' ELSE CTE.MAIN_TABLE_COLUMNS END\r\n\t\tELSE ''\r\n\t\tEND AS \"MAIN_TABLE_COLUMNS\",\r\n\tCASE WHEN (CTE.CONSTRAINT_TYPE = 'FOREIGN_KEY_CONSTRAINT') THEN '=>' ELSE ' |' END AS \"=>\",\r\n\tISNULL(CTE.REFER_TABLE_SCHEMA, '') AS REFER_TABLE_SCHEMA,\r\n\tISNULL(CTE.REFER_TABLE_NAME, '') AS REFER_TABLE_NAME,\r\n\tISNULL('PK: ' + CASE WHEN (CHARINDEX(',', CTE.REFER_TABLE_COLUMNS) > 0) THEN '( ' + CTE.REFER_TABLE_COLUMNS + ' )' ELSE CTE.REFER_TABLE_COLUMNS END, '') AS \"REFER_TABLE_COLUMNS\",\r\n\t'|' AS \"|||\",\r\n\tISNULL(CASE CTE.CONSTRAINT_TYPE\r\n\t\t\tWHEN 'FOREIGN_KEY_CONSTRAINT'\r\n\t\t\t\tTHEN 'FK:: Columns \" ' + CTE.MAIN_TABLE_COLUMNS + ' \" in Table \" ' + CTE.MAIN_TABLE_SCHEMA + '.' + CTE.MAIN_TABLE_NAME + ' \"' \r\n\t\t\t\t\t+ ' => REFERENCES => ' + 'PK:: Columns \" ' + CTE.REFER_TABLE_COLUMNS + ' \" in Table \" ' + CTE.REFER_TABLE_SCHEMA + '.' + CTE.REFER_TABLE_NAME + ' \"'\r\n\t\t\tELSE NULL\r\n\t\t\tEND, '') AS \"PRIMARYKEY_FOREIGNKEY_NOTATION\"\r\nFROM \r\n(\r\n\t--$BeginRegion: Getting Primary Keys and Unique Keys\r\n\tSELECT --\r\n\t\tKC.name AS CONSTRAINT_NAME,\r\n\t\tKC.type_desc AS CONSTRAINT_TYPE,\r\n\t\tNULL AS \"ON_UPDATE?\",\r\n\t\tNULL AS \"ON_DELETE?\",\r\n\t\tNULL AS \"IS_ENABLED?\",\r\n\t\tNULL AS \"IS_TRUSTED?\",\r\n\t\t--'|' AS \"||\"\r\n\t\tOBJECT_SCHEMA_NAME(KC.parent_object_id) AS MAIN_TABLE_SCHEMA,\r\n\t\tOBJECT_NAME(KC.parent_object_id) AS MAIN_TABLE_NAME,\r\n\t\tSTUFF((SELECT ', ' + C.NAME\r\n\t\t\t\tFROM sys.columns AS C\r\n\t\t\t\tINNER JOIN sys.index_columns AS IC ON IC.object_id = C.object_id AND IC.column_id = C.column_id\r\n\t\t\t\tWHERE C.object_id = KC.parent_object_id AND IC.index_id = KC.unique_index_id\r\n\t\t\t\tORDER BY IC.key_ordinal ASC FOR XML PATH('')), 1, 2, '') AS MAIN_TABLE_COLUMNS,\r\n\t\t--'' AS \"=>\",\r\n\t\tNULL AS REFER_TABLE_SCHEMA,\r\n\t\tNULL AS REFER_TABLE_NAME,\r\n\t\tNULL AS REFER_TABLE_COLUMNS\r\n\tFROM sys.key_constraints AS KC\r\n\t--$EndRegion: Getting Primary Keys and Unique Keys\r\n\tUNION ALL\r\n\t--$BeginRegion: Getting Foreign Keys\r\n\tSELECT --\r\n\t\tFK.NAME AS CONSTRAINT_NAME,\r\n\t\tFK.type_desc AS CONSTRAINT_TYPE,\r\n\t\tFK.update_referential_action_desc AS \"ON_UPDATE?\",\r\n\t\tFK.delete_referential_action_desc AS \"ON_DELETE?\",\r\n\t\tCASE FK.is_disabled WHEN 0 THEN 'YES' ELSE 'NO' END AS \"IS_ENABLED?\",\r\n\t\tCASE FK.is_not_trusted WHEN 0 THEN 'YES' ELSE 'NO' END AS \"IS_TRUSTED?\",\r\n\t\t--'|' AS \"||\"\r\n\t\tOBJECT_SCHEMA_NAME(FK.parent_object_id) AS MAIN_TABLE_SCHEMA,\r\n\t\tOBJECT_NAME(FK.parent_object_id) AS MAIN_TABLE_NAME,\r\n\t\tSTUFF((SELECT ', ' + C.NAME\r\n\t\t\t\tFROM sys.columns AS C\r\n\t\t\t\tINNER JOIN sys.foreign_key_columns AS KC ON C.object_id = KC.parent_object_id AND C.column_id = KC.parent_column_id\r\n\t\t\t\tWHERE KC.constraint_object_id = FK.object_id\r\n\t\t\t\tORDER BY KC.constraint_column_id FOR XML PATH('')), 1, 2, '') AS MAIN_TABLE_COLUMNS,\r\n\t\t--'' AS \"=>\",\r\n\t\tOBJECT_SCHEMA_NAME(FK.referenced_object_id) AS REFER_TABLE_SCHEMA,\r\n\t\tOBJECT_NAME(FK.referenced_object_id) AS REFER_TABLE_NAME,\r\n\t\tSTUFF((SELECT ', ' + C.name\r\n\t\t\t\tFROM sys.columns AS C\r\n\t\t\t\tINNER JOIN sys.foreign_key_columns AS KC ON C.object_id = KC.referenced_object_id AND C.column_id = KC.referenced_column_id\r\n\t\t\t\tWHERE KC.constraint_object_id = FK.object_id\r\n\t\t\t\tORDER BY KC.constraint_column_id FOR XML PATH('')), 1, 2, '') AS REFER_TABLE_COLUMNS\r\n\tFROM sys.foreign_keys AS FK\r\n\tWHERE FK.is_ms_shipped = 0\r\n\t--$EndRegion: Getting Foreign Keys\r\n)\r\nAS CTE\r\nWHERE 1 = 1\r\n\t--AND CONSTRAINT_NAME LIKE '%%'\r\n\t--AND CONSTRAINT_TYPE IN ('PRIMARY_KEY_CONSTRAINT', 'FOREIGN_KEY_CONSTRAINT', 'UNIQUE_CONSTRAINT')\r\n\t--AND [OnDelete?] IN ('NO_ACTION', 'CASCADE', 'SET_NULL', 'SET_DEFAULT')\r\n\t--AND [OnUpdate?] IN ('NO_ACTION', 'CASCADE', 'SET_NULL', 'SET_DEFAULT')\r\n\t--AND [IS_ENABLED?] IN ('YES', 'NO')\r\n\t--AND [IS_TRUSTED?] IN ('YES', 'NO')\r\n\t--AND MAIN_TABLE_SCHEMA LIKE '%%'\r\n\t--AND MAIN_TABLE_NAME LIKE '%%'\r\n\t--AND MAIN_TABLE_COLUMNS LIKE '%%'\r\n\t--AND REFER_TABLE_SCHEMA LIKE '%%'\r\n\t--AND REFER_TABLE_NAME LIKE '%%'\r\n\t--AND REFER_TABLE_COLUMNS LIKE '%%'"
}
{
"id": "13832a4f-7991-4fdf-a3da-42860d200356",
"prefix": "TDC_CreateCursor",
"description": "Create Cursor Syntax",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9886854Z",
"permissions": [],
"body": "DECLARE @$variable1$ $data_type1$,\n\t\t@$variable2$ $data_type2$;\t\t\t\t\t/* Declare All Required Variables */\n\nDECLARE $cursor_name$ CURSOR\t\t\t\t\t\t/* Declare Cursor Name */\n--[LOCAL | GLOBAL]\t\t\t\t\t\t\t\t/* Define Cursor Scope */\n--[FORWARD_ONLY | SCROLL]\t\t\t\t\t\t/* Define Movement Direction of Cursor */\n--[KEYSET | DYNAMIC | STATIC | FAST_FORWARD]\t/* Define Basic Type of Cursor */\n--[SCROLL_LOCKS | OPTIMISTIC | READ_ONLY]\t\t/* Define Locks */\nFOR (\n\tSELECT $column_name1$, $column_name2$\n\tFROM $schema_name$.$table_name$\n\tWHERE 1 = 1\n);\n\nOPEN $cursor_name$;\t\t\t\t\t\t\t\t\t\t\t\t/* Open Cursor */\n\nFETCH NEXT FROM $cursor_name$ INTO @$variable1$, @$variable2$;\t\t/* Fetch Data From Cursor */\n\nWHILE @@FETCH_STATUS = 0\nBEGIN\n\n\tSELECT @$variable1$, @$variable2$;\n\n\tFETCH NEXT FROM $cursor_name$ INTO @$variable1$, @$variable2$;\t/* Fetch Next Data From Cursor */\n\nEND;\n\nCLOSE $cursor_name$;\t\t\t\t\t\t\t\t\t\t\t\t/* Close The Cursor */\nDEALLOCATE $cursor_name$;\t\t\t\t\t\t\t\t\t\t\t/* DeAllocate all Resources and Memory */ ",
"placeholders": [
{
"name": "variable1",
"defaultValue": ""
},
{
"name": "data_type1",
"defaultValue": ""
},
{
"name": "variable2",
"defaultValue": ""
},
{
"name": "data_type2",
"defaultValue": ""
},
{
"name": "cursor_name",
"defaultValue": ""
},
{
"name": "column_name1",
"defaultValue": ""
},
{
"name": "column_name2",
"defaultValue": ""
},
{
"name": "schema_name",
"defaultValue": ""
},
{
"name": "table_name",
"defaultValue": ""
}
]
}
{
"id": "24ee6fb3-d2d2-494e-b1a1-e2e12e9fe191",
"prefix": "TDC_CreateDatabase",
"description": "Create Database",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9886854Z",
"permissions": [],
"body": "CREATE DATABASE $DatabaseName$\nON PRIMARY --PRIMARY FileGroup is Default Group\n\t( \n\t\tNAME = $DatabaseName$_data,\n\t\tFILENAME = '$DataFileLocationPath$\\$DatabaseName$_Data.mdf',\n\t\tSIZE = $DataFileInitialSize_KB$KB,\n\t\tFILEGROWTH = $DataFileGrowthSize_KB$KB\n\t),\n FILEGROUP $FileGroupName$ --SECONDARY FileGroup will be Created Automatically\n\t( \n\t\tNAME = $DatabaseName$_data2,\n\t\tFILENAME = '$DataFileLocationPath$\\$DatabaseName$_Data2.mdf',\n\t\tSIZE = $DataFileInitialSize_KB$KB,\n\t\tFILEGROWTH = $DataFileGrowthSize_KB$KB\n\t) -- Add Additional Files in FileGroups If Required\nLOG ON\n\t(\n\t\tNAME = $DatabaseName$_log,\n\t\tFILENAME = '$LogFileLocationPath$\\$DatabaseName$_Log.ldf',\n\t\tSIZE = $LogFileInitialSize_KB$KB,\n\t\tFILEGROWTH = $LogFileGrowthSize_KB$KB --(or) FILEGROWTH = 10%\n\t)\n;\nGO",
"placeholders": [
{
"name": "DatabaseName",
"defaultValue": ""
},
{
"name": "DataFileLocationPath",
"defaultValue": "C:\\MSSQLserver\\DATA"
},
{
"name": "LogFileLocationPath",
"defaultValue": "C:\\MSSQLserver\\LOG"
},
{
"name": "DataFileInitialSize_KB",
"defaultValue": "8192"
},
{
"name": "DataFileGrowthSize_KB",
"defaultValue": "2048"
},
{
"name": "FileGroupName",
"defaultValue": "SECONDARY"
},
{
"name": "LogFileInitialSize_KB",
"defaultValue": "8192"
},
{
"name": "LogFileGrowthSize_KB",
"defaultValue": "2048"
}
]
}
{
"id": "1a264945-bbf8-4514-80c2-246369a5c425",
"prefix": "TDC_CreateDatabaseSnapshot",
"description": "Create Database Snapshot",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9896854Z",
"permissions": [],
"body": "CREATE DATABASE $DatabaseName$ \nON (\n NAME = $DatabaseName$_data,\n FILENAME = '$SnapshotFileLocationPath$\\$DatabaseName$.ss'\n)\nAS SNAPSHOT OF $Source_DatabaseName$\nGO",
"placeholders": [
{
"name": "DatabaseName",
"defaultValue": ""
},
{
"name": "SnapshotFileLocationPath",
"defaultValue": "C:\\MSSQLserver"
},
{
"name": "Source_DatabaseName",
"defaultValue": ""
}
]
}
{
"id": "eb3edc75-942c-4906-9278-047ac334e98c",
"prefix": "TDC_CreateProc",
"description": "Create Stored Procedure",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9896854Z",
"permissions": [],
"body": "IF OBJECT_ID('[$dbo$].[$proc_name$]', 'P') IS NULL BEGIN\r\n\tEXEC('CREATE PROCEDURE [$dbo$].[$proc_name$] AS BEGIN SELECT 1; END;')\r\nEND \r\n\r\nGO\r\nALTER PROCEDURE [$dbo$].[$proc_name$] (@param1 INT)\r\nAS\r\nBEGIN\r\n\t/*\r\n\t\tAuthor: $USER$\r\n\t\tCreated: $DATE$ $TIME$\r\n\t\tPurpose: \r\n\t*/\r\n\tSET NOCOUNT ON \r\n\tSET XACT_ABORT ON\r\n\tBEGIN TRAN\r\n\r\n\tBEGIN TRY\r\n\t\t\t\r\n\t\t$CURSOR$SELECT @param1\r\n\t\tCOMMIT TRAN\r\n\tEND TRY\r\n\tBEGIN CATCH\r\n\t\t;THROW\t\r\n\tEND CATCH\r\nEND\r\nGO",
"placeholders": [
{
"name": "dbo",
"defaultValue": null
},
{
"name": "proc_name",
"defaultValue": null
}
]
}
{
"id": "833ae3c5-117d-4d39-ac1e-1a3dc568827e",
"prefix": "TDC_CreateSchema",
"description": "Create Schema",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9896854Z",
"permissions": [],
"body": "IF NOT EXISTS (SELECT * FROM sys.schemas WHERE name = N'$schema_name$')\n\tEXECUTE('CREATE SCHEMA $schema_name$');\nGO\n$CURSOR$",
"placeholders": [
{
"name": "schema_name",
"defaultValue": ""
}
]
}
{
"id": "fd677754-d1c1-4bb1-bc85-9817fa3e41f6",
"prefix": "TDC_CreateSplitFunction",
"description": "",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9896854Z",
"permissions": [],
"body": "IF OBJECT_ID('[dbo].[split]') IS NOT NULL\r\n\tDROP FUNCTION [dbo].[split];\r\n\r\nGO\r\nSET QUOTED_IDENTIFIER ON\r\nGO\r\nSET ANSI_NULLS ON\r\nGO\r\n\r\n\r\nCREATE FUNCTION [dbo].[split] (\r\n\t@pString VARCHAR(max), --WARNING!!! MAX DATA-TYPES MAY HURT PERFORMANCE!\r\n\t@pDelimiter VARCHAR(4)\r\n)\r\nRETURNS TABLE WITH SCHEMABINDING AS\r\nRETURN (\r\n\t/* CREDITS: \r\n\t\t\thttps://www.sqlservercentral.com/articles/tally-oh-an-improved-sql-8k-%E2%80%9Ccsv-splitter%E2%80%9D-function\r\n\t\t\thttp://www.sqlservercentral.com/articles/Tally+Table/72993/ \r\n\t\t\t\r\n\t\t\tBased upon the version from Jeff Moden, with some changes / improvements by Tim Cartwright\r\n\t*/\r\n\t/* Tim Cartwright: \r\n\t\t\t- modified to handle a varchar(?) delimiter, is changeable to other sizes if needed\r\n\t\t\t- modified to take a varchar(max) slight speed penalty, but allows for very large strings to be passed in. Can easily be reverted. Or split into two functions.\r\n\t\t\t- Added some cross apply functionality for speed improvements. \r\n\t\t\t- Changed the tally table generation to my preferred method of tally table gen. Much easier to read.c\r\n\t\tTESTS:\r\n\t\tSET NOCOUNT ON\r\n\t\t--EXEC sys.sp_helptext 'dbo.split'\r\n\t\tDECLARE @delim1\tvarchar(4)= '#-#' \r\n\t\t\t,@text1 varchar(max)\r\n\t\t--purposefully made the string contain the first character of the delimiter \r\n\t\tSELECT @text1 = stuff((\r\n\t\t\tSELECT TOP 10 + @delim1 + '#' + c.name + '#'\r\n\t\t\tFROM sys.columns c\r\n\t\t\tFOR XML PATH('') \r\n\t\t), 1, LEN(@delim1), '')\r\n\t\tSELECT [LEN(@text1)] = LEN(@text1), [@text1] = @text1\r\n\t\tSELECT * FROM dbo.split(@text1, @delim1) /* regular delimiter string */\r\n\t\tSELECT * FROM dbo.split(@delim1 + @text1, @delim1) /*delimiter at start */\r\n\t\tSELECT * FROM dbo.split(@text1 + @delim1, @delim1) /*delimiter at end*/\r\n\t\tSELECT * FROM dbo.split(@delim1 + @text1 + @delim1, @delim1) /*delimiter at start and end*/\r\n\t\tSELECT * FROM dbo.split(NULL, ',') /* null */\r\n\t\tSELECT * FROM dbo.split('\t', ',')\t/* empty string, space + tab */\r\n\t\tSELECT * FROM dbo.split('', ',')\t/* empty string */\r\n\t\tSELECT * FROM dbo.split('blah', ',')\t/* single string */\r\n\t\tSELECT * FROM dbo.split('blah,foo', ',')\t/* two strings */\r\n\t\tSELECT * FROM dbo.split(',blah,foo,', ',')\t/* two strings, delimiter at start and end */\r\n\t\tSELECT * FROM dbo.split('1,2,3', ',')\r\n\t\tSELECT * FROM dbo.split(',1,2,3,', ',')\r\n\t*/\r\n\t--===== \"Inline\" CTE Driven \"Tally Table\" \r\n\tWITH cteNumbers (N) AS\r\n\t(\r\n\t\tSELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL))\r\n\t\tFROM (\t VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) a(n)\t\t--10 rows\r\n\t\tCROSS JOIN (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) b(n)\t\t--100\r\n\t\tCROSS JOIN (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) c(n)\t\t--1,000\r\n\t\tCROSS JOIN (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) d(n)\t\t--10,000\r\n\t\tCROSS JOIN (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) e(n)\t\t--100,000\r\n\t\tCROSS JOIN (VALUES(0),(0),(0),(0),(0)) f(n)\t\t\t\t\t\t\t--500,000 /* if uncommenting out the below cross joins, ensure this one gets commented out as well*/\r\n\t\t--CROSS JOIN (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) f(n)\t--1,000,000 /* really don't think we will need these. besides, strings of this length are horrible on performance */\r\n\t\t--CROSS JOIN (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) g(n)\t--10,000,000\r\n\t\t--CROSS JOIN (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) h(n)\t--100,000,000\r\n\t),\r\n\tcteTally(N) AS (\r\n\t\t--==== This provides the \"base\" CTE and limits the number of rows right up front\r\n\t\t-- for both a performance gain and prevention of accidental \"overruns\"\r\n\t\tSELECT TOP (ISNULL(DATALENGTH(@pString),0)) num.N FROM cteNumbers num\r\n\t),\r\n\tcteStart(N1) AS (\r\n\t\t--==== This returns N+1 (starting position of each \"element\" just once for each delimiter)\r\n\t\tSELECT 1 UNION ALL\r\n\t\tSELECT t.N + fn.DelimLen \r\n\t\tFROM cteTally t \r\n\t\tCROSS APPLY ( SELECT StringLen = LEN(RTRIM(LTRIM(@pString))), DelimLen = LEN(@pDelimiter)) fn\r\n\t\tWHERE fn.StringLen > 0 AND SUBSTRING(@pString, t.N, fn.DelimLen) = @pDelimiter\r\n\t),\r\n\tcteLen(N1, L1) AS(\r\n\t\t--==== Return start and length (for use in substring)\r\n\t\t--SELECT s.N1, ISNULL(NULLIF(CHARINDEX(@pDelimiter,@pString,s.N1),0)-s.N1,8000) FROM cteStart s\r\n\t\tSELECT s.N1, CASE \r\n\t\t\tWHEN fn.StringLen = 0 THEN 0\r\n\t\t\tWHEN fnPos.[DelimPosition] = 0 THEN LEN(@pString) + 1\r\n\t\t\tELSE fnPos.[DelimPosition]\r\n\t\t\tEND\r\n\t\tFROM cteStart s\r\n\t\tCROSS APPLY (SELECT [StringLen] = LEN(RTRIM(LTRIM(@pString))), LikeClause = '%' + @pDelimiter + '%') fn\r\n\t\tCROSS APPLY (SELECT [DelimPosition] = PATINDEX(fn.LikeClause, SUBSTRING(@pString, s.N1, fn.StringLen))) fnPos\r\n\t)\r\n\t\r\n\tSELECT\tRowId\t= ROW_NUMBER() OVER(ORDER BY l.N1)\r\n\t\t\t,Value\t= fnVal.Val\r\n\t\t\t--,l.N1, l.L1, LEN(RTRIM(LTRIM(@pString))) AS [len]\r\n\tFROM cteLen l\r\n\tCROSS APPLY (SELECT [Val] = CASE \r\n\t\t\t\t\t\tWHEN l.L1 = 0 THEN NULL /* to handle a ' ' being passed in for @pString */ \r\n\t\t\t\t\t\tWHEN l.L1 = 1 AND l.N1 = 1 THEN NULL /* a delimiter was passed at the start of the string */\r\n\t\t\t\t\t\tWHEN LEN(RTRIM(LTRIM(@pString))) = (l.L1 - 1) AND l.L1 = l.N1 THEN NULL /* a delimiter was passed at the end of the string */\r\n\t\t\t\t\t\tELSE SUBSTRING(@pString, l.N1, l.L1 - 1) /* normal substring */\r\n\t\t\t\t\tEND) fnVal\r\n\tWHERE fnVal.Val IS NOT NULL\r\n)\r\n\r\n\r\nGO"
}
{
"id": "b54cf51d-d202-4950-855b-fbf5aa847c98",
"prefix": "TDC_CreateTable",
"description": "Create Table",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9906853Z",
"permissions": [],
"body": "IF OBJECT_ID('$schema_name$.$table_name$', 'U') IS NULL BEGIN\n\tCREATE TABLE $schema_name$.$table_name$ (\n\t\t[$column_name$] $data_type$ $null$,\n\t\tCONSTRAINT [PK_$table_name$_$column_name$] PRIMARY KEY CLUSTERED ($column_name$),\n\t) ON [$filegroup_name$];\nEND\nGO",
"placeholders": [
{
"name": "schema_name",
"defaultValue": "dbo"
},
{
"name": "table_name",
"defaultValue": ""
},
{
"name": "column_name",
"defaultValue": ""
},
{
"name": "data_type",
"defaultValue": ""
},
{
"name": "null",
"defaultValue": "NOT NULL"
},
{
"name": "filegroup_name",
"defaultValue": "PRIMARY"
}
]
}
{
"id": "320c10f4-4edf-4588-9eb2-4a7f5537180f",
"prefix": "TDC_CreateTableCK",
"description": "Adds a check constraint to a CreateTable statement",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9906853Z",
"permissions": [],
"body": "CONSTRAINT [CK_$table_name$_$column_name$] CHECK ($check$),",
"placeholders": [
{
"name": "table_name",
"defaultValue": null
},
{
"name": "column_name",
"defaultValue": null
},
{
"name": "check",
"defaultValue": null
}
]
}
{
"id": "e6e9a9de-c927-4e75-beeb-7c1582545f04",
"prefix": "TDC_CreateTableDF",
"description": "Adds a default to a CreateTable statement",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9906853Z",
"permissions": [],
"body": " CONSTRAINT [DF_$table_name$_$column_name$] DEFAULT ($default_value$)",
"placeholders": [
{
"name": "table_name",
"defaultValue": null
},
{
"name": "column_name",
"defaultValue": null
},
{
"name": "default_value",
"defaultValue": null
}
]
}
{
"id": "2205b48e-36ca-4970-ab57-8841228030d2",
"prefix": "TDC_CreateTableFK",
"description": "Adds a foreign key to a CreateTable statement",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9906853Z",
"permissions": [],
"body": "CONSTRAINT [FK_$table_name$_$fk_table_name$] FOREIGN KEY ([$column_name$]) REFERENCES [$fk_schema_name$].[$fk_table_name$] ([$column_name$]),",
"placeholders": [
{
"name": "table_name",
"defaultValue": null
},
{
"name": "fk_table_name",
"defaultValue": null
},
{
"name": "fk_schema_name",
"defaultValue": "dbo"
},
{
"name": "column_name",
"defaultValue": null
}
]
}
{
"id": "bd213740-bfa2-42fa-8706-f84be9761824",
"prefix": "TDC_CreateTableNC",
"description": "Adds a non clustered index to a CreateTable statement",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9916854Z",
"permissions": [],
"body": "INDEX [IX_$table_name$_$column_name$] NONCLUSTERED ([$column_name$])",
"placeholders": [
{
"name": "table_name",
"defaultValue": null
},
{
"name": "column_name",
"defaultValue": null
}
]
}
{
"id": "b8bf4611-2dbd-4c5d-81b4-c7e4df844d68",
"prefix": "TDC_CreateTempTable",
"description": "Create Temporary Table.",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9916854Z",
"permissions": [],
"body": "IF OBJECT_ID('tempdb.dbo.#$table_name$') IS NOT NULL\n\tDROP TABLE #$table_name$;\nGO\n\nCREATE TABLE #$table_name$ (\n\t$column_name1$ $data_type1$ PRIMARY KEY,\n\t$column_name2$ $data_type2$\n);\n$CURSOR$",
"placeholders": [
{
"name": "table_name",
"defaultValue": ""
},
{
"name": "column_name1",
"defaultValue": ""
},
{
"name": "data_type1",
"defaultValue": ""
},
{
"name": "column_name2",
"defaultValue": ""
},
{
"name": "data_type2",
"defaultValue": ""
}
]
}
{
"id": "28630416-08fb-461e-affe-04ad6d3a3e97",
"prefix": "TDC_DeclareTableVariable",
"description": "Declare Table Variable",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9916854Z",
"permissions": [],
"body": "DECLARE @$table_name$ TABLE (\n\t$column_name1$ $data_type1$ PRIMARY KEY,\n\t$column_name2$ $data_type2$\n);\n$CURSOR$",
"placeholders": [
{
"name": "table_name",
"defaultValue": ""
},
{
"name": "column_name1",
"defaultValue": ""
},
{
"name": "data_type1",
"defaultValue": ""
},
{
"name": "column_name2",
"defaultValue": ""
},
{
"name": "data_type2",
"defaultValue": ""
}
]
}
{
"id": "5343c742-87e9-4488-9d2b-af6730857ec4",
"prefix": "TDC_DisableAdvancedOptions",
"description": "Disabling Advanced Options",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9916854Z",
"permissions": [],
"body": "EXEC sys.sp_configure 'show advanced options', '0';\r\nRECONFIGURE;"
}
{
"id": "3ac7b024-b359-45fa-aaf7-282a34852b37",
"prefix": "TDC_DropAutoCreatedStatistics",
"description": "Drop Auto Created or System Created Statistics",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9926852Z",
"permissions": [],
"body": "DECLARE @SchemaName sysname,\r\n\t\t@TableName sysname,\r\n\t\t@AutoStatsName sysname;\r\nDECLARE @SQLcmd NVARCHAR(MAX) = '';\r\n\r\nDECLARE DropAutoStatsCursor CURSOR LOCAL FAST_FORWARD FOR (\r\n\tSELECT OBJECT_SCHEMA_NAME(object_id) AS SchemaName, OBJECT_NAME(object_id) AS TableName, name AS AutoStatsName\r\n\tFROM sys.stats\r\n\tWHERE OBJECT_SCHEMA_NAME(object_id) <> 'sys' --To Avoid Dropping System Statistics \r\n\t\t AND user_created = 0 --To Avoid Dropping User Created Statistics\r\n\t\t AND auto_created = 1 --To Consider and Drop Only Auto Created Statistics\r\n);\r\n\r\nOPEN DropAutoStatsCursor;\r\n\r\nFETCH NEXT FROM DropAutoStatsCursor INTO @SchemaName, @TableName, @AutoStatsName;\r\n\r\nWHILE @@FETCH_STATUS = 0\r\nBEGIN\r\n\tSET @SQLcmd = 'DROP STATISTICS ' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@TableName) + '.' + QUOTENAME(@AutoStatsName) + ';';\r\n\tEXEC sys.sp_executesql @statement = @SQLcmd;\r\n\tFETCH NEXT FROM DropAutoStatsCursor INTO @SchemaName, @TableName, @AutoStatsName;\r\nEND;\r\n\r\nCLOSE DropAutoStatsCursor;\r\nDEALLOCATE DropAutoStatsCursor;"
}
{
"id": "b6d07dc3-ddae-4590-842b-fa3ca0ac9f87",
"prefix": "TDC_DropColumn",
"description": "Drop Column If Already Exists",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9926852Z",
"permissions": [],
"body": "IF EXISTS (SELECT name FROM sys.columns WHERE object_id = OBJECT_ID(N'$schema_name$.$table_name$') AND name = N'$column_name$')\r\n\tALTER TABLE $schema_name$.$table_name$ DROP COLUMN $column_name$;\r\nGO\r\n\r\n$CURSOR$",
"placeholders": [
{
"name": "schema_name",
"defaultValue": null
},
{
"name": "table_name",
"defaultValue": null
},
{
"name": "column_name",
"defaultValue": null
}
]
}
{
"id": "b76f1e09-d700-4654-a844-36c2d111d35b",
"prefix": "TDC_DropDatabase",
"description": "Drop Database If Already Exists",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9926852Z",
"permissions": [],
"body": "USE [master]\r\n\r\nIF DB_ID('$database_name$') IS NOT NULL BEGIN\r\n\tEXEC msdb.dbo.sp_delete_database_backuphistory @database_name = N'$database_name$'\r\n\tALTER DATABASE [$database_name$] SET SINGLE_USER WITH ROLLBACK IMMEDIATE \r\n\tDROP DATABASE [$database_name$]\r\nEND\r\n",
"placeholders": [
{
"name": "database_name",
"defaultValue": null
}
]
}
{
"id": "97bbbf98-f443-4a0a-a600-6a720e7425df",
"prefix": "TDC_DropForeignKey",
"description": "Drop ForeignKey Constraint If Already Exists",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9926852Z",
"permissions": [],
"body": "IF OBJECT_ID('$foreignkey_constraint_name$', 'F') IS NOT NULL\r\n\tALTER TABLE $schema_name$.$table_name$ DROP CONSTRAINT $foreignkey_constraint_name$;\r\nGO",
"placeholders": [
{
"name": "table_name",
"defaultValue": ""
},
{
"name": "foreignkey_constraint_name",
"defaultValue": null
},
{
"name": "schema_name",
"defaultValue": null
}
]
}
{
"id": "c12dd62b-8b9e-47ed-8f19-dfdfa509cc27",
"prefix": "TDC_DropIndex",
"description": "Drop Index If Already Exists",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9936853Z",
"permissions": [],
"body": "IF EXISTS (SELECT name FROM sys.indexes WHERE object_id = OBJECT_ID(N'$SchemaName$.$TableName$') AND name = N'$IndexName$')\n\tDROP INDEX $IndexName$ ON $SchemaName$.$TableName$;\nGO\n\n$CURSOR$",
"placeholders": [
{
"name": "SchemaName",
"defaultValue": ""
},
{
"name": "TableName",
"defaultValue": ""
},
{
"name": "IndexName",
"defaultValue": ""
}
]
}
{
"id": "1df84dd5-c5d4-401e-8395-beae05efe6a2",
"prefix": "TDC_DropInlineTableValuedFunction",
"description": "Drop InlineTableValuedFunction If Already Exists",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9936853Z",
"permissions": [],
"body": "IF OBJECT_ID('$schema_name$.$InlineTableValuedFunction_name$', 'IF') IS NOT NULL\n\tDROP FUNCTION $schema_name$.$InlineTableValuedFunction_name$;\nGO\n\n$CURSOR$",
"placeholders": [
{
"name": "schema_name",
"defaultValue": ""
},
{
"name": "InlineTableValuedFunction_name",
"defaultValue": ""
}
]
}
{
"id": "41e9dec7-87cf-49b7-acfc-3bd2b5b70fb3",
"prefix": "TDC_DropJob",
"description": "Drop Job If Already Exists",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9936853Z",
"permissions": [],
"body": "IF EXISTS (SELECT 1 FROM msdb.dbo.sysjobs WHERE name = N'$JobName$')\r\n\tEXEC msdb.dbo.sp_delete_job --\r\n\t\t@job_name = '$JobName$',\r\n\t\t@delete_history = 1,\r\n\t\t@delete_unused_schedule = 1;\r\nGO",
"placeholders": [
{
"name": "JobName",
"defaultValue": null
}
]
}
{
"id": "989bdb39-9a43-4370-bc3e-0c86d9a5cdf5",
"prefix": "TDC_DropProcedure",
"description": "Drop Stored Procedure If Already Exists",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9936853Z",
"permissions": [],
"body": "IF OBJECT_ID('$schema_name$.$procedure_name$', 'P') IS NOT NULL\n\tDROP PROCEDURE $schema_name$.$procedure_name$;\nGO\n\n$CURSOR$",
"placeholders": [
{
"name": "schema_name",
"defaultValue": ""
},
{
"name": "procedure_name",
"defaultValue": ""
}
]
}
{
"id": "17580f04-b8c5-4dff-ae50-f18c185ba8ef",
"prefix": "TDC_DropScalarFunction",
"description": "Drop ScalarFunction If Already Exists",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9936853Z",
"permissions": [],
"body": "IF OBJECT_ID('$schema_name$.$ScalarFunction_name$', 'FN') IS NOT NULL\n\tDROP FUNCTION $schema_name$.$ScalarFunction_name$;\nGO\n\n$CURSOR$",
"placeholders": [
{
"name": "schema_name",
"defaultValue": ""
},
{
"name": "ScalarFunction_name",
"defaultValue": ""
}
]
}
{
"id": "43c4eb36-9473-439b-876b-2dd1dfd53508",
"prefix": "TDC_DropSchema",
"description": "Drop Schema If Already Exists",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9946852Z",
"permissions": [],
"body": "IF EXISTS (SELECT * FROM sys.schemas WHERE name = N'$schema_name$')\n\tDROP SCHEMA $schema_name$;\nGO\n\n$CURSOR$",
"placeholders": [
{
"name": "schema_name",
"defaultValue": ""
}
]
}
{
"id": "2d8c2725-2bec-4972-89bd-2cb3f4fc7a58",
"prefix": "TDC_DropTable",
"description": "Drop Table If Already Exists",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9946852Z",
"permissions": [],
"body": "IF OBJECT_ID('$schema_name$.$table_name$', 'U') IS NOT NULL\n\tDROP TABLE $schema_name$.$table_name$;\nGO\n\n$CURSOR$",
"placeholders": [
{
"name": "schema_name",
"defaultValue": ""
},
{
"name": "table_name",
"defaultValue": ""
}
]
}
{
"id": "e2f68f37-cc10-4762-8898-c1940543ed2f",
"prefix": "TDC_DropTableValuedFunction",
"description": "Drop TableValuedFunction If Already Exists",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9946852Z",
"permissions": [],
"body": "IF OBJECT_ID('$schema_name$.$TableValuedFunction_name$', 'TF') IS NOT NULL\n\tDROP FUNCTION $schema_name$.$TableValuedFunction_name$;\nGO\n\n$CURSOR$",
"placeholders": [
{
"name": "schema_name",
"defaultValue": ""
},
{
"name": "TableValuedFunction_name",
"defaultValue": ""
}
]
}
{
"id": "8e75b7da-0780-4956-8a82-4c9673ea3944",
"prefix": "TDC_DropTempTable",
"description": "Drop Temp Table If Already Exists",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9946852Z",
"permissions": [],
"body": "IF OBJECT_ID('tempdb..#$table_name$') IS NOT NULL\n\tDROP TABLE #$table_name$;\nGO\n\n$CURSOR$",
"placeholders": [
{
"name": "table_name",
"defaultValue": ""
}
]
}
{
"id": "d0c0ab3c-5755-49d1-aff8-1c6759497504",
"prefix": "TDC_DropTrigger",
"description": "Drop Trigger If Already Exists",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9956854Z",
"permissions": [],
"body": "IF OBJECT_ID('$schema_name$.$trigger_name$', 'TR') IS NOT NULL\n\tDROP TRIGGER $schema_name$.$trigger_name$;\nGO\n\n$CURSOR$",
"placeholders": [
{
"name": "schema_name",
"defaultValue": ""
},
{
"name": "trigger_name",
"defaultValue": ""
}
]
}
{
"id": "0c660065-bb61-4f4b-b08c-248ec87bbb36",
"prefix": "TDC_DropUserCreatedStatistics",
"description": "Drop User Created Statistics",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9956854Z",
"permissions": [],
"body": "DECLARE @SchemaName sysname,\r\n\t\t@TableName sysname,\r\n\t\t@UserStatsName sysname;\r\nDECLARE @SQLcmd NVARCHAR(MAX) = '';\r\n\r\nDECLARE DropUserStatsCursor CURSOR LOCAL FAST_FORWARD FOR\r\n(\r\n\tSELECT OBJECT_SCHEMA_NAME(object_id) AS SchemaName, OBJECT_NAME(object_id) AS TableName, name AS UserStatsName\r\n\tFROM sys.stats\r\n\tWHERE OBJECT_SCHEMA_NAME(object_id) <> 'sys' --To Avoid Dropping System Statistics \r\n\t\t AND auto_created = 0 --To Avoid Dropping Auto Created Statistics\r\n\t\t AND user_created = 1 --To Consider and Drop Only User Created Statistics\r\n);\r\n\r\nOPEN DropUserStatsCursor;\r\n\r\nFETCH NEXT FROM DropUserStatsCursor INTO @SchemaName, @TableName, @UserStatsName;\r\n\r\nWHILE @@FETCH_STATUS = 0\r\n\tBEGIN\r\n\t\tSET @SQLcmd = 'DROP STATISTICS ' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@TableName) + '.' + QUOTENAME(@UserStatsName) + ';';\r\n\t\tEXEC sys.sp_executesql @statement = @SQLcmd;\r\n\t\tFETCH NEXT FROM DropUserStatsCursor INTO @SchemaName, @TableName, @UserStatsName;\r\n\tEND;\r\n\r\nCLOSE DropUserStatsCursor;\r\nDEALLOCATE DropUserStatsCursor;"
}
{
"id": "9330471b-73ac-4c1d-b169-5296aab10b2f",
"prefix": "TDC_DropView",
"description": "Drop View If Already Exists",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9956854Z",
"permissions": [],
"body": "IF OBJECT_ID('$schema_name$.$view_name$', 'V') IS NOT NULL\n\tDROP VIEW $schema_name$.$view_name$;\nGO\n\n$CURSOR$",
"placeholders": [
{
"name": "schema_name",
"defaultValue": ""
},
{
"name": "view_name",
"defaultValue": ""
}
]
}
{
"id": "85bd4794-dc85-4b9a-a945-628be7b6c8a9",
"prefix": "TDC_DynamicSQL",
"description": "Execute Dynamic SQL Command",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9956854Z",
"permissions": [],
"body": "DECLARE @$variable_name$ NVARCHAR(MAX);\nSET @$variable_name$ = N'';\n\n--PRINT @$variable_name$;\nEXEC sys.sp_executesql @$variable_name$;",
"placeholders": [
{
"name": "variable_name",
"defaultValue": "SQLstring"
}
]
}
{
"id": "3b6cb789-fb7d-4c70-ada7-e96653978e4c",
"prefix": "TDC_EmailTableStyle1",
"description": "DBmail with Single Table Style1",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9966854Z",
"permissions": [],
"body": "DECLARE @XML NVARCHAR(MAX);\r\nDECLARE @Body NVARCHAR(MAX);\r\n\r\n--For ErrorFree, USE Same Format { ColumnName AS \"td\", '' }\r\nSET @XML = CAST((\r\n\t\t\t\t\tSELECT C.CategoryName AS \"td\", '',\r\n\t\t\t\t\t\t P.ProductName AS \"td\", '',\r\n\t\t\t\t\t\t P.Unit AS \"td\", '',\r\n\t\t\t\t\t\t P.Price AS \"td\", ''\r\n\t\t\t\t\tFROM dbo.Categories AS C\r\n\t\t\t\t\tINNER JOIN dbo.Products AS P\r\n\t\t\t\t\t\tON P.CategoryID = C.CategoryID\r\n\t\t\t\t\tWHERE C.CategoryID <= 3\r\n\t\t\t\t\tORDER BY C.CategoryName ASC\r\n\t\t\t\t\tFOR XML PATH('tr'), ELEMENTS\r\n\t\t\t\t) AS NVARCHAR(MAX));\r\n\r\nSET @Body = \r\nN'<html><body><H3>Sample Table Output Style</H3>\r\n<table border = 1>\r\n<tr>\r\n\t<th bgcolor=yellow><b> CategoryName </b></th>\r\n\t<th bgcolor=yellow><b> ProductName </b></th>\r\n\t<th bgcolor=yellow><b> Unit </b></th>\r\n\t<th bgcolor=yellow><b> Price </b></th>\r\n</tr>'\r\n+ @XML\r\n+ N'</table></body></html>';\r\n\r\nEXEC msdb.dbo.sp_send_dbmail --\r\n\t@profile_name = '$MailProfile$', --Replace with your SQL Database Mail Profile \r\n\t@body = @Body,\r\n\t@body_format = 'HTML',\r\n\t@recipients = '$ReceipientMailAddress$', --Replace with Receipient Email Address\r\n\t@subject = '$EmailSubjectHere$'; --Replace with Required SubjectText",
"placeholders": [
{
"name": "MailProfile",
"defaultValue": null
},
{
"name": "EmailSubjectHere",
"defaultValue": null
},
{
"name": "ReceipientMailAddress",
"defaultValue": null
}
]
}
{
"id": "ed9ba846-5a4c-4044-ba91-fbb4d7db259f",
"prefix": "TDC_EnableAdvancedOptions",
"description": "Enabling Advanced Options",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9966854Z",
"permissions": [],
"body": "EXEC sys.sp_configure 'show advanced options', '1';\r\nRECONFIGURE;"
}
{
"id": "d825bbfc-5bc0-4bba-a68d-5502bd4b7df0",
"prefix": "TDC_EnableCMDshell",
"description": "Enable xp_CMDshell",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9966854Z",
"permissions": [],
"body": "-- To Turn ON Advanced Options\r\nEXEC sys.sp_configure 'show advanced options', '1';\r\nRECONFIGURE;\r\n\r\n-- To Enable xp_cmdshell\r\nEXEC sys.sp_configure 'xp_cmdshell', '1';\r\nRECONFIGURE;\r\n\r\n-- To Turn OFF Advanced Options\r\nEXEC sys.sp_configure 'show advanced options', '0';\r\nRECONFIGURE;"
}
{
"id": "8a5107dc-01ec-4f11-bac6-8809acbabfc4",
"prefix": "TDC_Generate_TVC",
"description": "Automatically create a table variable (or temp table) in which to store the results of (for example) executing a stored procedure, function or query",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9966854Z",
"permissions": [],
"body": "/**\r\nCopyright (c) Red Gate Software Ltd 2021\r\nAll rights Reserved. Use of this code is subject to the terms of a license agreement with Red Gate Software Limited.\r\n\r\nThis is a temporary batch for creating such things as table variables, temporary tables or anything else that needs a column list.\r\nFor more info, see https://www.red-gate.com/hub/product-learning/sql-prompt/building-reusable-table-build-scripts-using-sql-prompt\r\n**/\r\n\r\nDeclare @TheExpression NVARCHAR(MAX)=\r\nN'$SELECTEDTEXT$'\r\n\r\nSELECT * FROM sys.dm_exec_describe_first_result_set (@TheExpression, NULL, 1) AS f\r\n\r\nSELECT 'DECLARE @$NameOfVariable$ table ('+\r\n Stuff ((SELECT ',\r\n '+QuoteName(Coalesce(DetectDuplicateNames.name+'_'+Convert(VARCHAR(5),f.column_ordinal),f.name))\r\n + ' '+ System_type_name + CASE WHEN is_nullable = 0 THEN ' NOT' ELSE ''END+' NULL'\r\n --+ CASE WHEN collation_name IS NULL THEN '' ELSE ' COLLATE '+collation_name END\r\n AS ThePath\r\n FROM sys.dm_exec_describe_first_result_set\r\n (@TheExpression, NULL, 1) AS f\r\n -- use sys.sp_describe_first_result_set for a batch\r\n LEFT OUTER JOIN \r\n (SELECT name AS name FROM sys.dm_exec_describe_first_result_set\r\n (@TheExpression, NULL, 0) WHERE is_hidden=0 \r\n GROUP BY name HAVING Count(*)>1) AS DetectDuplicateNames\r\n ON DetectDuplicateNames.name=f.name\r\n WHERE f.is_hidden=0\r\nORDER BY column_ordinal\r\nFOR XML PATH (''), TYPE).value('.', 'varchar(max)'),1,1,'')+')'",
"placeholders": [
{
"name": "NameOfVariable",
"defaultValue": "MyTableVariable"
}
]
}
{
"id": "b6324ac3-31fa-426f-9c8f-70fe7871a540",
"prefix": "TDC_GenerateServiceBrokerTrigger",
"description": "Generates a service broker trigger that alerts on table changes",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9986854Z",
"permissions": [],
"body": "\r\nSET NOCOUNT ON\r\nDROP TABLE IF EXISTS [#gen_columns]\r\n\r\n/**************************************************************/\r\n-- DO NOT MODIFY ABOVE THIS LINE\r\n/**************************************************************/\r\n/*****MODIFY TABLE NAME AND QUERY BELOW************************/\r\nDECLARE @table_name sysname = '[sys].[tables]'\r\n\r\nSELECT [name],\r\n [object_id],\r\n [principal_id],\r\n [schema_id],\r\n [parent_object_id],\r\n [type],\r\n [type_desc],\r\n [create_date],\r\n [modify_date],\r\n [is_ms_shipped],\r\n [is_published],\r\n [is_schema_published]\r\nINTO [#gen_columns] /* DO NOT CHANGE THIS INTO LINE */\r\nFROM sys.[tables] \r\nWHERE 1 <> 1 /* DO NOT CHANGE THIS LINE */\r\n/**************************************************************/\r\n-- DO NOT MODIFY BELOW THIS LINE\r\n/**************************************************************/\r\nDECLARE @objectId INT = OBJECT_ID(@table_name)\r\nDECLARE @triggerName sysname = CONCAT(QUOTENAME(OBJECT_SCHEMA_NAME(@objectId)), '.[tr_', OBJECT_SCHEMA_NAME(@objectId), '_', OBJECT_NAME(@objectId), '_SB_Notify]')\r\nDECLARE @message_name sysname = CONCAT(OBJECT_SCHEMA_NAME(@objectId), '_', OBJECT_NAME(@objectId))\r\nSET @table_name = CONCAT(QUOTENAME(OBJECT_SCHEMA_NAME(@objectId)), '.', QUOTENAME(OBJECT_NAME(@objectId)))\r\nDECLARE @tabtab CHAR(2) = REPLICATE(CHAR(9), 2)\r\n\r\nDECLARE @declare_columns VARCHAR(MAX) = (\r\n SELECT CONCAT(@tabtab, ' [record_row_number] INT IDENTITY', CHAR(10), @tabtab,\r\n STUFF((\r\n SELECT CONCAT(CHAR(10), @tabtab, ',', QUOTENAME(c.[name]), ' ', UPPER(t.[name]), \r\n CASE \r\n WHEN t.name LIKE '%char' OR t.name LIKE '%binary'\r\n THEN CONCAT(' (',\r\n CASE \r\n WHEN c.max_length=-1 THEN 'MAX'\r\n ELSE \r\n CAST(CASE \r\n WHEN t.name IN ('nchar','nvarchar') THEN c.max_length/2 \r\n ELSE c.max_length \r\n END AS VARCHAR(12)) \r\n END, ')'\r\n )\r\n WHEN t.name IN ('decimal','numeric')\r\n THEN CONCAT('(', c.precision, ',', c.Scale, ')')\r\n WHEN t.name = 'datetime2'\r\n THEN CONCAT('(', c.scale, ')')\r\n ELSE '' \r\n END, ' NULL'\r\n ) \r\n FROM [tempdb].sys.[columns] AS [c] \r\n INNER JOIN [tempdb].sys.[types] AS [t] ON [t].[user_type_id] = [c].[user_type_id]\r\n WHERE [c].[object_id] = OBJECT_ID('tempdb..#gen_columns')\r\n FOR XML PATH('')\r\n ),1,3, '')\r\n )\r\n)\r\nDECLARE @columns VARCHAR(MAX) = (\r\n SELECT STUFF((\r\n SELECT CONCAT(', ', QUOTENAME(c.[name]))\r\n FROM [tempdb].sys.[columns] AS [c] \r\n INNER JOIN [tempdb].sys.[types] AS [t] ON [t].[user_type_id] = [c].[user_type_id]\r\n WHERE [c].[object_id] = OBJECT_ID('tempdb..#gen_columns')\r\n FOR XML PATH('')\r\n ), 1, 2, '')\r\n)\r\n\r\nPRINT '\r\nSET ANSI_NULLS ON\r\nGO\r\nSET QUOTED_IDENTIFIER ON\r\nGO\r\n'\r\nPRINT CONCAT('CREATE OR ALTER TRIGGER ', @triggerName, ' ON ', @table_name) \r\nPRINT 'AFTER INSERT, UPDATE, DELETE AS\r\nBEGIN\r\n SET NOCOUNT ON\r\n \r\n -- if true, then rows where none of the values have changed will be removed from update messages\r\n DECLARE @removeZeroChangeRows bit = 1,\r\n @processRow int = 0,\r\n @conversation uniqueidentifier\r\n'\r\n\r\nPRINT ' DECLARE @modifiedRecords TABLE ('\r\nPRINT @declare_columns\r\nPRINT ' )'\r\nPRINT ' DECLARE @deletedRecords TABLE ('\r\nPRINT @declare_columns\r\nPRINT ' )'\r\n\r\nPRINT ' DECLARE @action VARCHAR(10) = CASE \r\n WHEN EXISTS(SELECT 1 FROM INSERTED) AND EXISTS(SELECT 1 FROM DELETED) THEN ''UPDATE''\r\n WHEN EXISTS(SELECT 1 FROM INSERTED) THEN ''INSERT''\r\n ELSE ''DELETE''\r\n END;'\r\n\r\nPRINT CONCAT(' DECLARE @messageType varchar(500) = CONCAT(''', @message_name, ''', ''/'', @action),\r\n @environment VARCHAR(100) = (SELECT CAST([ep].[value] AS VARCHAR(100)) FROM master.sys.[extended_properties] AS [ep] WHERE [ep].[name] = ''environment'' AND [ep].[major_id] = 0)')\r\n\r\nPRINT CONCAT('\r\n IF @action = ''DELETE'' BEGIN\r\n INSERT INTO @deletedRecords \r\n (', @columns, ')\r\n SELECT \r\n ', @columns, '\r\n FROM DELETED \r\n SELECT @processRow = MIN([record_row_number]) FROM @deletedRecords\r\n END ELSE IF @action = ''UPDATE'' BEGIN\r\n INSERT INTO @modifiedRecords \r\n (', @columns, ')\r\n SELECT \r\n ', @columns, ' \r\n FROM INSERTED \r\n INSERT INTO @deletedRecords \r\n (', @columns, ')\r\n SELECT \r\n ', @columns, '\r\n FROM DELETED\r\n IF @removeZeroChangeRows = 1 BEGIN\r\n DELETE mr\r\n FROM @modifiedRecords mr\r\n WHERE EXISTS ( \r\n SELECT \r\n ', REPLACE(@columns, '[', 'mr.['), ' \r\n INTERSECT \r\n SELECT \r\n ', @columns, ' \r\n FROM @deletedRecords\r\n )\r\n END\r\n SELECT @processRow = MIN([record_row_number]) FROM @modifiedRecords\r\n END ELSE IF @action = ''INSERT'' BEGIN\r\n INSERT INTO @modifiedRecords \r\n (', @columns, ')\r\n SELECT \r\n ', @columns, '\r\n FROM INSERTED \r\n SELECT @processRow = MIN([record_row_number]) FROM @modifiedRecords\r\n END\r\n IF @processRow > 0 BEGIN\r\n /****USE CTRL+SHIFT+M TO ALTER THIS STATEMENT**********************/\r\n BEGIN DIALOG @conversation\r\n FROM SERVICE <sender_service, sysname, sender_service>\r\n TO SERVICE N''<recipient_service, sysname, recipient_service>''\r\n ON CONTRACT <contract_name, sysname, contract_name>\r\n WITH ENCRYPTION=OFF;\r\n DECLARE @json NVARCHAR(MAX) \r\n BEGIN TRY\r\n WHILE @processRow > 0\r\n BEGIN\r\n -- custom attributes can be added to the xml generation\r\n SET @json = (\r\n SELECT \r\n LOWER(@action) as [action],\r\n @environment AS [environment],\r\n @@SERVERNAME AS [server_name],\r\n DB_NAME() AS [db_name],\r\n GETUTCDATE() AS [utc_server_datetime], (\r\n SELECT \r\n ', @columns, '\r\n FROM @deletedRecords\r\n WHERE record_row_number = @processRow\r\n FOR JSON PATH, WITHOUT_ARRAY_WRAPPER \r\n ) AS [Old], (\r\n SELECT \r\n ', @columns, ' \r\n FROM @modifiedRecords\r\n WHERE record_row_number = @processRow\r\n FOR JSON PATH, WITHOUT_ARRAY_WRAPPER \r\n ) AS [New]\r\n FOR JSON PATH, ROOT(''Record'')\r\n )\r\n --PRINT CONCAT(''ROW:'', @processRow, '' = '', @json, CHAR(13), CHAR(10))\r\n ;SEND ON CONVERSATION @conversation MESSAGE TYPE @messageType (@json);\r\n IF @action <> ''DELETE'' BEGIN\r\n SELECT @processRow = ISNULL(MIN(record_row_number), -1) FROM @modifiedRecords WHERE [record_row_number] > @processRow\r\n END ELSE BEGIN\r\n SELECT @processRow = ISNULL(MIN(record_row_number), -1) FROM @deletedRecords WHERE [record_row_number] > @processRow\r\n END\r\n END\r\n END TRY\r\n BEGIN CATCH\r\n ;THROW\r\n END CATCH;\r\n END\r\n')\r\n\r\nPRINT 'END\r\nGO'\r\n"
}
{
"id": "caefeb23-ef3f-41e3-b767-e59fff0afef5",
"prefix": "TDC_GetLoginInfo",
"description": "",
"body": "DECLARE @login VARCHAR(512) = ORIGINAL_LOGIN()\r\nEXEC xp_logininfo @login, 'all'\r\n"
}
{
"id": "33986f83-a085-483c-ab93-e2dd8f622f36",
"prefix": "TDC_GetTableFromQuery",
"description": "Generates a table from a query. Source: Red-Gate",
"body": "/**\r\nCopyright (c) Red Gate Software Ltd 2021\r\nAll rights Reserved. Use of this code is subject to the terms of a license agreement with Red Gate Software Limited.\r\n\r\nThis is a temporary batch for creating such things as table variables, temporary tables or anything else that needs a column list.\r\nFor more info, see https://www.red-gate.com/hub/product-learning/sql-prompt/building-reusable-table-build-scripts-using-sql-prompt\r\n**/\r\n\r\nDeclare @TheExpression NVARCHAR(MAX)=\r\nN'$SELECTEDTEXT$'\r\n\r\nSELECT 'DECLARE @$NameOfVariable$ table ('+\r\n Stuff ((SELECT ',\r\n '+QuoteName(Coalesce(DetectDuplicateNames.name+'_'+Convert(VARCHAR(5),f.column_ordinal),f.name))\r\n + ' '+ System_type_name + CASE WHEN is_nullable = 0 THEN ' NOT' ELSE ''END+' NULL'\r\n --+ CASE WHEN collation_name IS NULL THEN '' ELSE ' COLLATE '+collation_name END\r\n AS ThePath\r\n FROM sys.dm_exec_describe_first_result_set\r\n (@TheExpression, NULL, 1) AS f\r\n -- use sys.sp_describe_first_result_set for a batch\r\n LEFT OUTER JOIN \r\n (SELECT name AS name FROM sys.dm_exec_describe_first_result_set\r\n (@TheExpression, NULL, 0) WHERE is_hidden=0 \r\n GROUP BY name HAVING Count(*)>1) AS DetectDuplicateNames\r\n ON DetectDuplicateNames.name=f.name\r\n WHERE f.is_hidden=0\r\nORDER BY column_ordinal\r\nFOR XML PATH (''), TYPE).value('.', 'varchar(max)'),1,1,'')+')'",
"placeholders": [
{
"name": "NameOfVariable",
"defaultValue": null
}
]
}
{
"id": "b48663de-27ba-4636-a554-14f51d26518b",
"prefix": "TDC_IfExists",
"description": "If Exists",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9996853Z",
"permissions": [],
"body": "IF EXISTS (\n\tSELECT 1\n\tFROM $schema_name$.$table_name$\n\tWHERE 1 = 1 -- AND $filter$\n)\nBEGIN\n\t$CURSOR$$PRINT 'Exists'\nEND",
"placeholders": [
{
"name": "schema_name",
"defaultValue": ""
},
{
"name": "table_name",
"defaultValue": ""
},
{
"name": "filter",
"defaultValue": ""
}
]
}
{
"id": "4e9aafcc-4c78-431e-9011-8747513ce00d",
"prefix": "TDC_IfNotExists",
"description": "If Not Exists",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:25.9996853Z",
"permissions": [],
"body": "IF NOT EXISTS (\n\tSELECT 1\n\tFROM $schema_name$.$table_name$\n\tWHERE 1 = 1 -- AND $filter$\n)\nBEGIN\n\t$CURSOR$PRINT 'Not Exists'\nEND",
"placeholders": [
{
"name": "schema_name",
"defaultValue": ""
},
{
"name": "table_name",
"defaultValue": ""
},
{
"name": "filter",
"defaultValue": ""
}
]
}
{
"id": "f87487c2-1ae0-4225-9f4b-fe4f5547f2ea",
"prefix": "TDC_Index_FindHeaps",
"description": "",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:26.0006853Z",
"permissions": [],
"body": "SELECT SCHEMA_NAME(o.schema_id), o.name, i.type_desc, o.type_desc, o.create_date\r\nFROM sys.indexes i\r\nINNER JOIN sys.objects o\r\n ON i.object_id = o.object_id\r\nWHERE o.type_desc = 'USER_TABLE'\r\nAND i.type_desc = 'HEAP'\r\nORDER BY o.name"
}
{
"id": "88adf664-c159-4f78-87a6-53709e32994a",
"prefix": "TDC_Index_FindLotsOfIncludes",
"description": "",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:26.0006853Z",
"permissions": [],
"body": "IF OBJECT_ID('tempdb..#indexes') IS NOT NULL BEGIN\r\n DROP TABLE #indexes\r\nEND\r\n\r\nCREATE TABLE #indexes (\r\n\tDBName sysname null,\r\n\tObjectName sysname null,\r\n\tIndexName sysname null,\r\n\t[Index_Columns] varchar(max),\r\n\t[Index_Includes] varchar(max)\r\n)\r\n\r\nEXEC [sys].[sp_MSforeachdb] N'\r\n\tUSE [?];\r\n\tIF DB_ID() <= 4 RETURN;\r\n\t \r\n\tINSERT INTO [#indexes]\r\n\t\t([DBName], [ObjectName], [IndexName], [Index_Columns], [Index_Includes])\r\n\tSELECT DB_NAME(), \r\n\t\tOBJECT_NAME(i.[object_id]), \r\n\t\ti.[name], \r\n\t\t[Columns] = (SELECT STUFF((\r\n\t\t\t\tSELECT '', '' + c.name \r\n\t\t\t\tFROM sys.[index_columns] ic\r\n\t\t\t\tINNER JOIN sys.[columns] c ON [ic].[object_id] = [c].[object_id] AND [ic].[column_id] = [c].[column_id] \r\n\t\t\t\tWHERE [ic].[object_id] = [i].[object_id]\r\n\t\t\t\t\tAND [ic].[index_id] = [i].[index_id]\r\n\t\t\t\t\tAND [ic].[is_included_column] = 0\r\n\t\t\t\tFOR XML PATH('''')\r\n\t\t\t), 1, 1, '''')),\r\n\t\t[Includes] = (SELECT STUFF((\r\n\t\t\t\tSELECT '', '' + c.name \r\n\t\t\t\tFROM sys.[index_columns] ic\r\n\t\t\t\tINNER JOIN sys.[columns] c ON [ic].[object_id] = [c].[object_id] AND [ic].[column_id] = [c].[column_id] \r\n\t\t\t\tWHERE [ic].[object_id] = [i].[object_id]\r\n\t\t\t\t\tAND [ic].[index_id] = [i].[index_id]\r\n\t\t\t\t\tAND [ic].[is_included_column] = 1\r\n\t\t\t\tFOR XML PATH('''')\r\n\t\t\t), 1, 1, ''''))\r\n\tFROM sys.[indexes] i\r\n\tCROSS APPLY (\r\n\t\tSELECT\t[index_columns_count] = ISNULL((SELECT count(*) FROM [sys].[index_columns] ic WHERE ic.[object_id] = i.[object_id] AND ic.[index_id] = i.[index_id]), 0),\r\n\t\t\t\t[columns_count] = ISNULL((SELECT count(*) FROM sys.[columns] c WHERE c.[object_id] = i.[object_id]), 0)\r\n\t) fnCnt\r\n\tWHERE OBJECTPROPERTY(i.[object_id], ''ISMsShipped'') = 0\r\n\t\tAND i.[index_id] <> 1\r\n\t\tAND fnCnt.columns_count > 3\r\n\t\tAND fnCnt.index_columns_count >= (fnCnt.columns_count * 0.80)'\r\n\r\nSELECT * FROM [#indexes] i\r\n\r\nIF OBJECT_ID('tempdb..#indexes') IS NOT NULL BEGIN\r\n DROP TABLE #indexes\r\nEND\r\n\r\n--AND ic.[is_included_column] = 1"
}
{
"id": "3c1fb201-d742-4d90-860a-db959fa933ca",
"prefix": "TDC_Index_FindUnIndexedForeignKeys",
"description": "",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:26.0006853Z",
"permissions": [],
"body": "SELECT *\r\nFROM sys.foreign_keys fk\r\nWHERE EXISTS\r\n (\r\n SELECT *\r\n FROM sys.foreign_key_columns fkc\r\n WHERE fkc.constraint_object_id = fk.object_id\r\n AND NOT EXISTS\r\n (\r\n SELECT *\r\n FROM sys.index_columns ic\r\n WHERE ic.object_id = fkc.parent_object_id\r\n AND ic.column_id = fkc.parent_column_id\r\n )\r\n )"
}
{
"id": "4e5bfe47-31ae-4790-aed2-2f83768e3b00",
"prefix": "TDC_Index_FindUnused",
"description": "",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:26.0006853Z",
"permissions": [],
"body": "SELECT [object_name] = OBJECT_NAME(us.[object_id]),\r\n\t[index_name] = i.[name],\r\n\tus.user_seeks,\r\n\tus.user_scans,\r\n\tus.user_lookups,\r\n\tus.user_updates, \r\n\t[index_size_mb] = FORMAT(SUM(ps.[used_page_count]) / 128.0, 'N2') \r\nFROM sys.dm_db_index_usage_stats AS us\r\nINNER JOIN sys.indexes AS i\r\n ON i.[object_id] = us.[object_id]\r\n AND i.index_id = us.index_id\r\nINNER JOIN sys.dm_db_partition_stats ps \r\n\tON ps.index_id = i.index_id \r\n\t\tAND ps.object_id = i.object_id\r\nWHERE OBJECTPROPERTY(us.[object_id], 'IsUserTable') = 1\r\n AND us.database_id = DB_ID()\r\n AND us.user_seeks = 0\r\n AND us.user_scans = 0\r\n AND us.user_lookups = 0\r\nGROUP BY us.[object_id],\r\n\ti.[name],\r\n\tus.user_seeks,\r\n\tus.user_scans,\r\n\tus.user_lookups,\r\n\tus.user_updates\r\nORDER BY 1, i.name;"
}
{
"id": "dd53625a-7ec9-4a19-b39b-fa744a8f2e9d",
"prefix": "TDC_Index_FindWide",
"description": "",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:26.0016854Z",
"permissions": [],
"body": "IF OBJECT_ID('tempdb..#indexes') IS NOT NULL BEGIN\r\n DROP TABLE #indexes\r\nEND\r\n\r\nCREATE TABLE #indexes (\r\n\tDBName sysname null,\r\n\tObjectName sysname null,\r\n\tIndexName sysname null,\r\n\t[Index_Columns] varchar(max),\r\n\t[Index_Includes] varchar(max),\r\n\t[Table_Columns] varchar(max),\r\n\t[Reason] varchar(40)\r\n)\r\n\r\nEXEC [sys].[sp_MSforeachdb] N'\r\nUSE [?];\r\nIF DB_ID() <= 4 RETURN;\r\n\t \r\nINSERT INTO [#indexes]\r\n\t([DBName], [ObjectName], [IndexName], [Index_Columns], [Index_Includes], [Table_Columns], [Reason])\r\nSELECT DB_NAME(), \r\n\tOBJECT_NAME(i.[object_id]), \r\n\ti.[name], \r\n\t[Columns] = (SELECT STUFF((\r\n\t\tSELECT '', '' + c.name + '' '' + TYPE_NAME(c.[user_type_id]) + ''('' + CASE c.[max_length] WHEN -1 THEN ''max'' ELSE CAST(c.[max_length] AS varchar(20)) END + '')''\r\n\t\tFROM sys.[index_columns] ic\r\n\t\tINNER JOIN sys.[columns] c ON [ic].[object_id] = [c].[object_id] AND [ic].[column_id] = [c].[column_id] \r\n\t\tWHERE [ic].[object_id] = [i].[object_id] AND [ic].[index_id] = [i].[index_id] AND [ic].[is_included_column] = 0\r\n\t\tFOR XML PATH('''')\r\n\t), 1, 1, '''')),\r\n\t[Includes] = (SELECT STUFF((\r\n\t\tSELECT '', '' + c.name + '' '' + TYPE_NAME(c.[user_type_id]) + ''('' + CASE c.[max_length] WHEN -1 THEN ''max'' ELSE CAST(c.[max_length] AS varchar(20)) END + '')''\r\n\t\tFROM sys.[index_columns] ic\r\n\t\tINNER JOIN sys.[columns] c ON [ic].[object_id] = [c].[object_id] AND [ic].[column_id] = [c].[column_id] \r\n\t\tWHERE [ic].[object_id] = [i].[object_id] AND [ic].[index_id] = [i].[index_id] AND [ic].[is_included_column] = 1\r\n\t\tFOR XML PATH('''')\r\n\t), 1, 1, '''')),\r\n\t[Table_Columns] = (SELECT STUFF((\r\n\t\tSELECT '', '' + c.name \r\n\t\tFROM sys.[columns] c \r\n\t\tWHERE [i].[object_id] = [c].[object_id] \r\n\t\tFOR XML PATH('''')\r\n\t), 1, 1, '''')),\r\n\t''Column Count''\r\nFROM sys.[indexes] i\r\nCROSS APPLY (\r\n\tSELECT [index_columns_count] = ISNULL((SELECT count(*) FROM [sys].[index_columns] ic WHERE ic.[object_id] = i.[object_id] AND ic.[index_id] = i.[index_id]), 0),\r\n\t\t[columns_count] = ISNULL((SELECT count(*) FROM sys.[columns] c WHERE c.[object_id] = i.[object_id]), 0)\r\n) fnCnt\r\nWHERE OBJECTPROPERTY(i.[object_id], ''ISMsShipped'') = 0 \r\nAND i.[index_id] <> 1 \r\nAND fnCnt.columns_count > 4 \r\nAND fnCnt.index_columns_count >= (fnCnt.columns_count * 0.80)'\r\n\r\n--had to seperate these into two seperate loops as the query was too long combined\r\nEXEC [sys].[sp_MSforeachdb] N'\r\nUSE [?];\r\nIF DB_ID() <= 4 RETURN;\r\n\t \r\nINSERT INTO [#indexes]\r\n\t([DBName], [ObjectName], [IndexName], [Index_Columns], [Index_Includes], [Table_Columns], [Reason])\r\nSELECT DB_NAME(), \r\n\tOBJECT_NAME(i.[object_id]), \r\n\ti.[name], \r\n\t[Columns] = (SELECT STUFF((\r\n\t\tSELECT '', '' + c.name + '' '' + TYPE_NAME(c.[user_type_id]) + ''('' + CASE c.[max_length] WHEN -1 THEN ''max'' ELSE CAST(c.[max_length] AS varchar(20)) END + '')''\r\n\t\tFROM sys.[index_columns] ic\r\n\t\tINNER JOIN sys.[columns] c ON [ic].[object_id] = [c].[object_id] AND [ic].[column_id] = [c].[column_id] \r\n\t\tWHERE [ic].[object_id] = [i].[object_id] AND [ic].[index_id] = [i].[index_id] AND [ic].[is_included_column] = 0\r\n\t\tFOR XML PATH('''')\r\n\t), 1, 1, '''')),\r\n\t[Includes] = (SELECT STUFF((\r\n\t\tSELECT '', '' + c.name + '' '' + TYPE_NAME(c.[user_type_id]) + ''('' + CASE c.[max_length] WHEN -1 THEN ''max'' ELSE CAST(c.[max_length] AS varchar(20)) END + '')''\r\n\t\tFROM sys.[index_columns] ic\r\n\t\tINNER JOIN sys.[columns] c ON [ic].[object_id] = [c].[object_id] AND [ic].[column_id] = [c].[column_id] \r\n\t\tWHERE [ic].[object_id] = [i].[object_id] AND [ic].[index_id] = [i].[index_id] AND [ic].[is_included_column] = 1\r\n\t\tFOR XML PATH('''')\r\n\t), 1, 1, '''')),\r\n\t[Table_Columns] = (SELECT STUFF((\r\n\t\tSELECT '', '' + c.name \r\n\t\tFROM sys.[columns] c \r\n\t\tWHERE [i].[object_id] = [c].[object_id] \r\n\t\tFOR XML PATH('''')\r\n\t), 1, 1, '''')),\r\n\t''Wide Columns''\r\nFROM sys.[indexes] i\r\nCROSS APPLY (\r\n\tSELECT [wide_index_columns_count] = ISNULL((SELECT count(*) \r\n\t\tFROM sys.[index_columns] ic \r\n\t\tINNER JOIN sys.[columns] c ON [ic].[object_id] = [c].[object_id] AND [ic].[column_id] = [c].[column_id]\r\n\t\tINNER JOIN sys.[types] t ON [c].[user_type_id] = [t].[user_type_id]\r\n\t\tWHERE (ic.[object_id] = i.[object_id] AND ic.[index_id] = i.[index_id] ) \r\n\t\t\tAND (t.[name] LIKE ''%char'' OR t.[name] = ''xml'')\r\n\t\t\tAND (c.[max_length] >= 1000 OR c.[max_length] = -1)\r\n\t\t), 0)\r\n) fnCnt\r\nWHERE fnCnt.[wide_index_columns_count] > 0\r\n'\r\n\r\n;WITH cteRows AS (\r\n\tSELECT [rownbr] = ROW_NUMBER() OVER (PARTITION BY [i].[DBName], [i].[ObjectName], [i].[IndexName] ORDER BY [i].[DBName], [i].[ObjectName], [i].[IndexName], [i].[Reason]), * \r\n\tFROM [#indexes] i\r\n)\r\n--SELECT * FROM cterows\r\n\r\nSELECT t1.[DBName], t1.[ObjectName], t1.[IndexName], \r\n\tt1.[Index_Columns], t1.[Index_Includes], t1.[Table_Columns], \r\n\t[Reason] = CASE WHEN t2.[Reason] IS NULL THEN t1.[Reason] ELSE CONCAT(t1.[Reason], ', ', t2.[Reason]) END\r\nFROM cteRows t1 \r\nLEFT JOIN cteRows t2 ON t1.[DBName] = t2.[DBName]\r\n\tAND t1.[ObjectName] = t2.[ObjectName]\r\n\tAND t1.[IndexName] = t2.[IndexName]\r\n\tAND t1.[rownbr] = 1 \r\n\tAND t2.[rownbr] = 2\r\nWHERE t1.[rownbr] = 1\r\nORDER BY t1.[DBName], \r\n\tt1.[ObjectName], \r\n\tt1.[IndexName]\r\n\r\n--IF OBJECT_ID('tempdb..#indexes') IS NOT NULL BEGIN\r\n-- DROP TABLE #indexes\r\n--END"
}
{
"id": "6af89bfa-9f64-4b48-94e9-1ddd2a2232d8",
"prefix": "TDC_Index_Fragmentation",
"description": "",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:26.0016854Z",
"permissions": [],
"body": "SELECT OBJECT_NAME(ips.OBJECT_ID) [ObjectName]\r\n\t, i.name\r\n\t, i.[fill_factor]\r\n\t, [ips].[alloc_unit_type_desc]\r\n\t, index_type_desc\r\n\t, index_level\r\n\t, avg_fragmentation_in_percent\r\n\t, avg_page_space_used_in_percent\r\n\t, page_count\r\nFROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL , 'LIMITED') ips\r\ninner join sys.indexes i \r\n\ton ips.object_id = i.object_id and ips.index_id = i.index_id\r\nORDER BY avg_fragmentation_in_percent DESC\r\n"
}
{
"id": "9fefe3d4-fc4d-4747-b35c-023c087494bf",
"prefix": "TDC_Index_Statistics",
"description": "",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:26.0016854Z",
"permissions": [],
"body": "SELECT [schema_name] = s.[name],\r\n\t[table_name] = t.[name],\r\n\t[index_name] = i.[name],\r\n\tips.[avg_fragmentation_in_percent], \r\n\tips.[avg_fragment_size_in_pages], \r\n\t[i].[type], \r\n\tips.[index_type_desc], \r\n\tips.[alloc_unit_type_desc], \r\n\tips.[page_count], \r\n\t[page_count_mb] = CAST(ips.[page_count] / 128.0 as money), \r\n\tst.[user_seeks], \r\n\tst.[user_scans], \r\n\tst.[user_lookups], \r\n\tst.[user_updates],\r\n\tips.[index_depth], \r\n\t--FOLLOWING FIELDS ARE NULL WHEN USING 'LIMITED'\r\n\tips.[record_count], \r\n\tips.[forwarded_record_count],\r\n\tips.[ghost_record_count],\r\n\tips.[version_ghost_record_count],\r\n\tips.[min_record_size_in_bytes],\r\n\tips.[avg_record_size_in_bytes],\r\n\tips.[max_record_size_in_bytes],\r\n\t--FOLLOWING FIELDS ARE NULL WHEN USING 'SAMPLED'\r\n\tips.[fragment_count]\r\nFROM sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL, NULL, 'LIMITED') AS ips -- LIMITED, SAMPLED, DETAILED (SUPER SLOW, AND HEAVY PERFORMANCE COSTS)\r\nINNER JOIN sys.tables t on t.[object_id] = ips.[object_id]\r\nINNER JOIN sys.schemas s on t.[schema_id] = s.[schema_id]\r\nINNER JOIN sys.indexes AS i ON i.[object_id] = ips.[object_id] AND ips.index_id = i.index_id\r\nINNER JOIN sys.dm_db_index_usage_stats st ON [i].[object_id] = [st].[object_id] AND [i].[index_id] = [st].[index_id] \r\nWHERE ips.database_id = DB_ID() \r\n\tAND st.[database_id] = DB_ID()\r\n--\tAND (st.[user_seeks] = 0 AND ips.[index_type_desc] = 'NONCLUSTERED INDEX')\r\n--\tAND t.[object_id] = OBJECT_ID('dbo.Foo')\r\nORDER BY s.[name],\r\n\tt.[name],\r\n\ti.[index_id]"
}
{
"id": "38c63c71-dc80-4972-8c5c-eb2c2e0e1b5e",
"prefix": "TDC_LoginUserMappings",
"description": "",
"body": "-- https://www.sqlserver-dba.com/2015/01/how-to-list-sql-logins-and-database-user-mappings.html\r\nIF OBJECT_ID('tempdb..#tempMappings') IS NOT NULL\r\n\tDROP TABLE #tempMappings;\r\nGO\r\n\r\nCREATE TABLE #tempMappings (\r\n\t[login_name] sysname,\r\n\t[db_name] sysname NULL,\r\n\t[user_name] sysname NULL,\r\n\t[alias] sysname NULL\r\n)\r\nINSERT INTO #tempMappings\r\nEXEC master.dbo.sp_msloginmappings\r\n \r\nSELECT *\r\nFROM #tempMappings \r\nWHERE [db_name] IS NOT NULL\r\n\tAND [user_name] IS NOT NULL\r\n\tAND [login_name] NOT IN ('sa')\r\n\tAND [login_name] NOT LIKE '##%'\r\nORDER BY [user_name], \r\n\t[db_name]\r\n\r\n"
}
{
"id": "9f4ad2a6-f4cc-4e99-95ba-fcfc57e966b1",
"prefix": "TDC_ManyPlansForQueryHash",
"description": "",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:26.0016854Z",
"permissions": [],
"body": "-- https://eitanblumin.com/2022/08/25/too-many-plans-for-the-same-query-hash/\r\n-- https://github.com/MadeiraData/MadeiraToolbox/blob/master/Health%20Check%20Scripts/Many%20Plans%20for%20Single%20Query%20Hash.sql\r\n\r\nDECLARE\r\n\t@RCA bit = 1,\r\n\t@MinimumSizeInPlanCacheMB int = 256,\r\n\t@Top int = 10,\r\n\t@PlanCountThreshold int = 5,\r\n\t@CountByPlanHandleInsteadOfPlanHash bit = 0\r\n;\r\nSET NOCOUNT, ARITHABORT, XACT_ABORT ON;\r\nSET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;\r\nDECLARE @PlanCacheTotalSize decimal(19,2);\r\nSELECT @PlanCacheTotalSize = CAST(SUM(CONVERT(bigint, size_in_bytes)) / 1024.0 / 1024.0 AS DECIMAL(19,2))\r\nFROM sys.dm_exec_cached_plans\r\n\r\nDECLARE @Result AS TABLE\r\n(\r\n QueryHash binary(8),\r\n DistinctPlans int,\r\n DatabaseId int,\r\n TotalSizeMB decimal(19,2)\r\n)\r\n\r\nDECLARE @DBsCount int;\r\nSELECT @DBsCount = COUNT(*) FROM sys.databases;\r\n\r\nIF @PlanCountThreshold < @DBsCount\r\n\tSET @PlanCountThreshold = @DBsCount * 2;\r\n\r\nINSERT INTO @Result\r\nSELECT TOP (@Top)\r\n qs.query_hash\r\n , COUNT(DISTINCT (CASE WHEN @CountByPlanHandleInsteadOfPlanHash = 1 THEN qs.plan_handle ELSE qs.query_plan_hash END))\r\n , CAST(pa.value AS int)\r\n , CAST(SUM(ts.totalSize) / 1024.0 / 1024.0 AS decimal(19,2)) AS totalSize\r\nFROM sys.dm_exec_query_stats qs\r\nCROSS APPLY sys.dm_exec_plan_attributes(qs.plan_handle) pa\r\nCROSS APPLY\r\n(\r\n\tSELECT totalSize = SUM(CONVERT(bigint, size_in_bytes))\r\n\tFROM sys.dm_exec_cached_plans AS cp\r\n\tWHERE cp.plan_handle = qs.plan_handle\r\n) AS ts\r\nWHERE pa.attribute = 'dbid'\r\nGROUP BY qs.query_hash, pa.value\r\nHAVING COUNT(DISTINCT (CASE WHEN @CountByPlanHandleInsteadOfPlanHash = 1 THEN qs.plan_handle ELSE qs.query_plan_hash END)) >= @PlanCountThreshold\r\nORDER BY totalSize DESC\r\nOPTION (RECOMPILE);\r\n\r\nIF @RCA = 1\r\nBEGIN\r\n\tSELECT QueryHash, query_plan_hash, DistinctPlans, DB_NAME(DatabaseId) AS DatabaseName, TotalSizeMB, TotalSizeMB / @PlanCacheTotalSize * 100 AS PercentOfTotalCache\r\n\t, qplan.query_plan AS example_query_plan, qtext.text AS example_sql_batch\r\n\t, StatsPerQueryPlanHashCmd = N';\r\n\tWITH QueryPlanHashes\r\n\tAS\r\n\t(\r\n\tSELECT TOP (' + CONVERT(nvarchar(max), @Top) + N') qs.query_plan_hash, qs.query_hash\r\n\t, TotalDistinctExecPlans = COUNT(*)\r\n\t, TotalExecutionCount = SUM(qs.execution_count)\r\n\t, TotalWorkerTime = SUM(qs.total_worker_time)\r\n\t, TotalElapsedTime = SUM(qs.total_elapsed_time)\r\n\t, TotalPhysicalReads = SUM(qs.total_physical_reads)\r\n\t, TotalLogicalReads = SUM(qs.total_logical_reads)\r\n\t, TotalLogicalWrites = SUM(qs.total_logical_writes)\r\n\t, TotalGrantKB = SUM(qs.total_grant_kb)\r\n\t, TotalUsedGrantKB = SUM(qs.total_used_grant_kb)\r\n\tFROM sys.dm_exec_query_stats AS qs\r\n\tWHERE qs.query_hash = ' + CONVERT(nvarchar(max), res.QueryHash, 1) + N'\r\n\tGROUP BY qs.query_plan_hash, qs.query_hash\r\n\tORDER BY TotalExecutionCount DESC, TotalElapsedTime DESC\r\n\t)\r\n\tSELECT qs.*\r\n\t, ExampleQueryPlan = ex.query_plan\r\n\t, ExampleQueryText = ex.text\r\n\tFROM QueryPlanHashes AS qs\r\n\tCROSS APPLY (\r\n\t\tSELECT TOP 1 qplan.query_plan, txt.text\r\n\t\tFROM sys.dm_exec_query_stats AS qs2\r\n\t\tCROSS APPLY sys.dm_exec_query_plan(qs2.plan_handle) AS qplan\r\n\t\tCROSS APPLY sys.dm_exec_sql_text(qs2.sql_handle) AS txt\r\n\t\tWHERE qs2.query_hash = qs.query_hash\r\n\t\tAND qs2.query_plan_hash = qs.query_plan_hash\r\n\t\tORDER BY qs2.execution_count DESC\r\n\t\t) AS ex'\r\n\t, MoreDetailsCmd = N'\r\n\tSELECT TOP (' + CONVERT(nvarchar(max), @Top) + N')\r\n\tClearPlanHandleFromCacheCmd = N''DBCC FREEPROCCACHE ('' + CONVERT(nvarchar(max), qs.plan_handle, 1) + N'');''\r\n\t, qplan.query_plan, qs.query_plan_hash, txt.text, qs.*\r\n\tFROM sys.dm_exec_query_stats AS qs\r\n\tCROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qplan\r\n\tCROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS txt\r\n\tWHERE qs.query_hash = ' + CONVERT(nvarchar(max), res.QueryHash, 1) + N'\r\n\tORDER BY qs.execution_count DESC'\r\n\t, ClearSqlHandleFromCacheCmd = N'DBCC FREEPROCCACHE (' + CONVERT(nvarchar(max), qs_p_handle.sql_handle, 1) + N');'\r\n\tFROM @Result AS res\r\n\tCROSS APPLY\r\n\t(\r\n\t\tSELECT TOP 1 qs.plan_handle, qs.sql_handle, qs.query_plan_hash\r\n\t\tFROM sys.dm_exec_query_stats AS qs\r\n\t\tWHERE qs.query_hash = res.QueryHash\r\n\t\tORDER BY qs.execution_count DESC\r\n\t) AS qs_p_handle\r\n\tCROSS APPLY sys.dm_exec_query_plan(qs_p_handle.plan_handle) AS qplan\r\n\tCROSS APPLY sys.dm_exec_sql_text(qs_p_handle.sql_handle) AS qtext\r\n\tWHERE TotalSizeMB >= @MinimumSizeInPlanCacheMB\r\n\tOPTION(RECOMPILE);\r\nEND\r\nELSE\r\nBEGIN\r\n\tSELECT\r\n\tMsg = N'Possible parameterization issues for Query Hash '\r\n\t+ CONVERT(nvarchar(max), QueryHash, 1) + N' in database ' + QUOTENAME(DB_NAME(DatabaseId))\r\n\t+ N': ' + CONVERT(nvarchar(max), DistinctPlans) + N' plans (' + CONVERT(nvarchar(max), TotalSizeMB) + N' MB which is '\r\n\t+ CONVERT(nvarchar(max), CONVERT(decimal(5,2), TotalSizeMB / @PlanCacheTotalSize * 100)) + N' % of plan cache)'\r\n\t, PlanCachePercent = CONVERT(decimal(5,2), TotalSizeMB / @PlanCacheTotalSize * 100)\r\n\tFROM @Result\r\n\tWHERE TotalSizeMB >= @MinimumSizeInPlanCacheMB\r\n\tOPTION(RECOMPILE);\r\nEND"
}
{
"id": "f486d8c5-3090-4fff-9965-8ca1d03820ce",
"prefix": "TDC_mvpAM_sp_WhoIsActive",
"description": "sp_WhoIsActive (By Adam Machanic)",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:26.0026853Z",
"permissions": [],
"body": "SET QUOTED_IDENTIFIER ON;\r\nSET ANSI_PADDING ON;\r\nSET CONCAT_NULL_YIELDS_NULL ON;\r\nSET ANSI_WARNINGS ON;\r\nSET NUMERIC_ROUNDABORT OFF;\r\nSET ARITHABORT ON;\r\nGO\r\n\r\nIF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_NAME = 'sp_WhoIsActive')\r\n EXEC ('CREATE PROC dbo.sp_WhoIsActive AS SELECT ''stub version, to be replaced''')\r\nGO\r\n\r\n/*********************************************************************************************\r\nWho Is Active? v12.00 (2021-11-10)\r\n(C) 2007-2021, Adam Machanic\r\n\r\nFeedback: https://github.com/amachanic/sp_whoisactive/issues\r\nReleases: https://github.com/amachanic/sp_whoisactive/releases\r\nDocs: http://whoisactive.com\r\n\r\nLicense:\r\n https://github.com/amachanic/sp_whoisactive/blob/master/LICENSE\r\n*********************************************************************************************/\r\nALTER PROC dbo.sp_WhoIsActive\r\n(\r\n--~\r\n --Filters--Both inclusive and exclusive\r\n --Set either filter to '' to disable\r\n --Valid filter types are: session, program, database, login, and host\r\n --Session is a session ID, and either 0 or '' can be used to indicate \"all\" sessions\r\n --All other filter types support % or _ as wildcards\r\n @filter sysname = '',\r\n @filter_type VARCHAR(10) = 'session',\r\n @not_filter sysname = '',\r\n @not_filter_type VARCHAR(10) = 'session',\r\n\r\n --Retrieve data about the calling session?\r\n @show_own_spid BIT = 0,\r\n\r\n --Retrieve data about system sessions?\r\n @show_system_spids BIT = 0,\r\n\r\n --Controls how sleeping SPIDs are handled, based on the idea of levels of interest\r\n --0 does not pull any sleeping SPIDs\r\n --1 pulls only those sleeping SPIDs that also have an open transaction\r\n --2 pulls all sleeping SPIDs\r\n @show_sleeping_spids TINYINT = 1,\r\n\r\n --If 1, gets the full stored procedure or running batch, when available\r\n --If 0, gets only the actual statement that is currently running in the batch or procedure\r\n @get_full_inner_text BIT = 0,\r\n\r\n --Get associated query plans for running tasks, if available\r\n --If @get_plans = 1, gets the plan based on the request's statement offset\r\n --If @get_plans = 2, gets the entire plan based on the request's plan_handle\r\n @get_plans TINYINT = 0,\r\n\r\n --Get the associated outer ad hoc query or stored procedure call, if available\r\n @get_outer_command BIT = 0,\r\n\r\n --Enables pulling transaction log write info, transaction duration, and the\r\n --implicit_transaction identification column\r\n @get_transaction_info BIT = 0,\r\n\r\n --Get information on active tasks, based on three interest levels\r\n --Level 0 does not pull any task-related information\r\n --Level 1 is a lightweight mode that pulls the top non-CXPACKET wait, giving preference to blockers\r\n --Level 2 pulls all available task-based metrics, including:\r\n --number of active tasks, current wait stats, physical I/O, context switches, and blocker information\r\n @get_task_info TINYINT = 1,\r\n\r\n --Gets associated locks for each request, aggregated in an XML format\r\n @get_locks BIT = 0,\r\n\r\n --Get average time for past runs of an active query\r\n --(based on the combination of plan handle, sql handle, and offset)\r\n @get_avg_time BIT = 0,\r\n\r\n --Get additional non-performance-related information about the session or request\r\n --text_size, language, date_format, date_first, quoted_identifier, arithabort, ansi_null_dflt_on,\r\n --ansi_defaults, ansi_warnings, ansi_padding, ansi_nulls, concat_null_yields_null,\r\n --transaction_isolation_level, lock_timeout, deadlock_priority, row_count, command_type\r\n --\r\n --If a SQL Agent job is running, an subnode called agent_info will be populated with some or all of\r\n --the following: job_id, job_name, step_id, step_name, msdb_query_error (in the event of an error)\r\n --\r\n --If @get_task_info is set to 2 and a lock wait is detected, a subnode called block_info will be\r\n --populated with some or all of the following: lock_type, database_name, object_id, file_id, hobt_id,\r\n --applock_hash, metadata_resource, metadata_class_id, object_name, schema_name\r\n @get_additional_info BIT = 0,\r\n\r\n --Get additional information related to workspace memory\r\n --requested_memory, granted_memory, max_used_memory, and memory_info.\r\n --\r\n --Not available for SQL Server 2005.\r\n @get_memory_info BIT = 0,\r\n\r\n --Walk the blocking chain and count the number of\r\n --total SPIDs blocked all the way down by a given session\r\n --Also enables task_info Level 1, if @get_task_info is set to 0\r\n @find_block_leaders BIT = 0,\r\n\r\n --Pull deltas on various metrics\r\n --Interval in seconds to wait before doing the second data pull\r\n @delta_interval TINYINT = 0,\r\n\r\n --List of desired output columns, in desired order\r\n --Note that the final output will be the intersection of all enabled features and all\r\n --columns in the list. Therefore, only columns associated with enabled features will\r\n --actually appear in the output. Likewise, removing columns from this list may effectively\r\n --disable features, even if they are turned on\r\n --\r\n --Each element in this list must be one of the valid output column names. Names must be\r\n --delimited by square brackets. White space, formatting, and additional characters are\r\n --allowed, as long as the list contains exact matches of delimited valid column names.\r\n @output_column_list VARCHAR(8000) = '[dd%][session_id][sql_text][sql_command][login_name][wait_info][tasks][tran_log%][cpu%][temp%][block%][reads%][writes%][context%][physical%][query_plan][locks][%]',\r\n\r\n --Column(s) by which to sort output, optionally with sort directions.\r\n --Valid column choices:\r\n --session_id, physical_io, reads, physical_reads, writes, tempdb_allocations,\r\n --tempdb_current, CPU, context_switches, used_memory, physical_io_delta, reads_delta,\r\n --physical_reads_delta, writes_delta, tempdb_allocations_delta, tempdb_current_delta,\r\n --CPU_delta, context_switches_delta, used_memory_delta, tasks, tran_start_time,\r\n --open_tran_count, blocking_session_id, blocked_session_count, percent_complete,\r\n --host_name, login_name, database_name, start_time, login_time, program_name\r\n --\r\n --Note that column names in the list must be bracket-delimited. Commas and/or white\r\n --space are not required.\r\n @sort_order VARCHAR(500) = '[start_time] ASC',\r\n\r\n --Formats some of the output columns in a more \"human readable\" form\r\n --0 disables outfput format\r\n --1 formats the output for variable-width fonts\r\n --2 formats the output for fixed-width fonts\r\n @format_output TINYINT = 1,\r\n\r\n --If set to a non-blank value, the script will attempt to insert into the specified\r\n --destination table. Please note that the script will not verify that the table exists,\r\n --or that it has the correct schema, before doing the insert.\r\n --Table can be specified in one, two, or three-part format\r\n @destination_table VARCHAR(4000) = '',\r\n\r\n --If set to 1, no data collection will happen and no result set will be returned; instead,\r\n --a CREATE TABLE statement will be returned via the @schema parameter, which will match\r\n --the schema of the result set that would be returned by using the same collection of the\r\n --rest of the parameters. The CREATE TABLE statement will have a placeholder token of\r\n --<table_name> in place of an actual table name.\r\n @return_schema BIT = 0,\r\n @schema VARCHAR(MAX) = NULL OUTPUT,\r\n\r\n --Help! What do I do?\r\n @help BIT = 0\r\n--~\r\n)\r\n/*\r\nOUTPUT COLUMNS\r\n--------------\r\nFormatted/Non: [session_id] [smallint] NOT NULL\r\n Session ID (a.k.a. SPID)\r\n\r\nFormatted: [dd hh:mm:ss.mss] [varchar](15) NULL\r\nNon-Formatted: <not returned>\r\n For an active request, time the query has been running\r\n For a sleeping session, time since the last batch completed\r\n\r\nFormatted: [dd hh:mm:ss.mss (avg)] [varchar](15) NULL\r\nNon-Formatted: [avg_elapsed_time] [int] NULL\r\n (Requires @get_avg_time option)\r\n How much time has the active portion of the query taken in the past, on average?\r\n\r\nFormatted: [physical_io] [varchar](30) NULL\r\nNon-Formatted: [physical_io] [bigint] NULL\r\n Shows the number of physical I/Os, for active requests\r\n\r\nFormatted: [reads] [varchar](30) NULL\r\nNon-Formatted: [reads] [bigint] NULL\r\n For an active request, number of reads done for the current query\r\n For a sleeping session, total number of reads done over the lifetime of the session\r\n\r\nFormatted: [physical_reads] [varchar](30) NULL\r\nNon-Formatted: [physical_reads] [bigint] NULL\r\n For an active request, number of physical reads done for the current query\r\n For a sleeping session, total number of physical reads done over the lifetime of the session\r\n\r\nFormatted: [writes] [varchar](30) NULL\r\nNon-Formatted: [writes] [bigint] NULL\r\n For an active request, number of writes done for the current query\r\n For a sleeping session, total number of writes done over the lifetime of the session\r\n\r\nFormatted: [tempdb_allocations] [varchar](30) NULL\r\nNon-Formatted: [tempdb_allocations] [bigint] NULL\r\n For an active request, number of TempDB writes done for the current query\r\n For a sleeping session, total number of TempDB writes done over the lifetime of the session\r\n\r\nFormatted: [tempdb_current] [varchar](30) NULL\r\nNon-Formatted: [tempdb_current] [bigint] NULL\r\n For an active request, number of TempDB pages currently allocated for the query\r\n For a sleeping session, number of TempDB pages currently allocated for the session\r\n\r\nFormatted: [CPU] [varchar](30) NULL\r\nNon-Formatted: [CPU] [bigint] NULL\r\n For an active request, total CPU time consumed by the current query\r\n For a sleeping session, total CPU time consumed over the lifetime of the session\r\n\r\nFormatted: [context_switches] [varchar](30) NULL\r\nNon-Formatted: [context_switches] [bigint] NULL\r\n Shows the number of context switches, for active requests\r\n\r\nFormatted: [used_memory] [varchar](30) NOT NULL\r\nNon-Formatted: [used_memory] [bigint] NOT NULL\r\n For an active request, total memory consumption for the current query\r\n For a sleeping session, total current memory consumption\r\n\r\nFormatted: [max_used_memory] [varchar](30) NULL\r\nNon-Formatted: [max_used_memory] [bigint] NULL\r\n (Requires @get_memory_info = 1)\r\n For an active request, the maximum amount of memory that has been used during\r\n processing up to the point of observation for the current query\r\n\r\nFormatted: [requested_memory] [varchar](30) NULL\r\nNon-Formatted: [requested_memory] [bigint] NULL\r\n (Requires @get_memory_info = 1)\r\n For an active request, the amount of memory requested by the query processor\r\n for hash, sort, and parallelism operations\r\n\r\nFormatted: [granted_memory] [varchar](30) NULL\r\nNon-Formatted: [granted_memory] [bigint] NULL\r\n (Requires @get_memory_info = 1)\r\n For an active request, the amount of memory granted to the query processor\r\n for hash, sort, and parallelism operations\r\n\r\nFormatted: [physical_io_delta] [varchar](30) NULL\r\nNon-Formatted: [physical_io_delta] [bigint] NULL\r\n (Requires @delta_interval option)\r\n Difference between the number of physical I/Os reported on the first and second collections.\r\n If the request started after the first collection, the value will be NULL\r\n\r\nFormatted: [reads_delta] [varchar](30) NULL\r\nNon-Formatted: [reads_delta] [bigint] NULL\r\n (Requires @delta_interval option)\r\n Difference between the number of reads reported on the first and second collections.\r\n If the request started after the first collection, the value will be NULL\r\n\r\nFormatted: [physical_reads_delta] [varchar](30) NULL\r\nNon-Formatted: [physical_reads_delta] [bigint] NULL\r\n (Requires @delta_interval option)\r\n Difference between the number of physical reads reported on the first and second collections.\r\n If the request started after the first collection, the value will be NULL\r\n\r\nFormatted: [writes_delta] [varchar](30) NULL\r\nNon-Formatted: [writes_delta] [bigint] NULL\r\n (Requires @delta_interval option)\r\n Difference between the number of writes reported on the first and second collections.\r\n If the request started after the first collection, the value will be NULL\r\n\r\nFormatted: [tempdb_allocations_delta] [varchar](30) NULL\r\nNon-Formatted: [tempdb_allocations_delta] [bigint] NULL\r\n (Requires @delta_interval option)\r\n Difference between the number of TempDB writes reported on the first and second collections.\r\n If the request started after the first collection, the value will be NULL\r\n\r\nFormatted: [tempdb_current_delta] [varchar](30) NULL\r\nNon-Formatted: [tempdb_current_delta] [bigint] NULL\r\n (Requires @delta_interval option)\r\n Difference between the number of allocated TempDB pages reported on the first and second\r\n collections. If the request started after the first collection, the value will be NULL\r\n\r\nFormatted: [CPU_delta] [varchar](30) NULL\r\nNon-Formatted: [CPU_delta] [int] NULL\r\n (Requires @delta_interval option)\r\n Difference between the CPU time reported on the first and second collections.\r\n If the request started after the first collection, the value will be NULL\r\n\r\nFormatted: [context_switches_delta] [varchar](30) NULL\r\nNon-Formatted: [context_switches_delta] [bigint] NULL\r\n (Requires @delta_interval option)\r\n Difference between the context switches count reported on the first and second collections\r\n If the request started after the first collection, the value will be NULL\r\n\r\nFormatted: [used_memory_delta] [varchar](30) NULL\r\nNon-Formatted: [used_memory_delta] [bigint] NULL\r\n Difference between the memory usage reported on the first and second collections\r\n If the request started after the first collection, the value will be NULL\r\n\r\nFormatted: [max_used_memory_delta] [varchar](30) NULL\r\nNon-Formatted: [max_used_memory_delta] [bigint] NULL\r\n Difference between the max memory usage reported on the first and second collections\r\n If the request started after the first collection, the value will be NULL\r\n\r\nFormatted: [tasks] [varchar](30) NULL\r\nNon-Formatted: [tasks] [smallint] NULL\r\n Number of worker tasks currently allocated, for active requests\r\n\r\nFormatted/Non: [status] [varchar](30) NOT NULL\r\n Activity status for the session (running, sleeping, etc)\r\n\r\nFormatted/Non: [wait_info] [nvarchar](4000) NULL\r\n Aggregates wait information, in the following format:\r\n (Ax: Bms/Cms/Dms)E\r\n A is the number of waiting tasks currently waiting on resource type E. B/C/D are wait\r\n times, in milliseconds. If only one thread is waiting, its wait time will be shown as B.\r\n If two tasks are waiting, each of their wait times will be shown (B/C). If three or more\r\n tasks are waiting, the minimum, average, and maximum wait times will be shown (B/C/D).\r\n If wait type E is a page latch wait and the page is of a \"special\" type (e.g. PFS, GAM, SGAM),\r\n the page type will be identified.\r\n If wait type E is CXPACKET, CXCONSUMER, CXSYNC_PORT, or CXSYNC_CONSUMER the nodeId from the\r\n query plan will be identified\r\n\r\nFormatted/Non: [locks] [xml] NULL\r\n (Requires @get_locks option)\r\n Aggregates lock information, in XML format.\r\n The lock XML includes the lock mode, locked object, and aggregates the number of requests.\r\n Attempts are made to identify locked objects by name\r\n\r\nFormatted/Non: [tran_start_time] [datetime] NULL\r\n (Requires @get_transaction_info option)\r\n Date and time that the first transaction opened by a session caused a transaction log\r\n write to occur.\r\n\r\nFormatted/Non: [tran_log_writes] [nvarchar](4000) NULL\r\n (Requires @get_transaction_info option)\r\n Aggregates transaction log write information, in the following format:\r\n A:wB (C kB)\r\n A is a database that has been touched by an active transaction\r\n B is the number of log writes that have been made in the database as a result of the transaction\r\n C is the number of log kilobytes consumed by the log records\r\n\r\nFormatted/Non: [implicit_tran] [nvarchar](3) NULL\r\n (Requires @get_transaction_info option)\r\n For active read-write transactions, returns on \"ON\" the transaction has been started as a result\r\n of the session using the implicit_transactions option, or \"OFF\" otherwise.\r\n\r\nFormatted: [open_tran_count] [varchar](30) NULL\r\nNon-Formatted: [open_tran_count] [smallint] NULL\r\n Shows the number of open transactions the session has open\r\n\r\nFormatted: [sql_command] [xml] NULL\r\nNon-Formatted: [sql_command] [nvarchar](max) NULL\r\n (Requires @get_outer_command option)\r\n Shows the \"outer\" SQL command, i.e. the text of the batch or RPC sent to the server,\r\n if available\r\n\r\nFormatted: [sql_text] [xml] NULL\r\nNon-Formatted: [sql_text] [nvarchar](max) NULL\r\n Shows the SQL text for active requests or the last statement executed\r\n for sleeping sessions, if available in either case.\r\n If @get_full_inner_text option is set, shows the full text of the batch.\r\n Otherwise, shows only the active statement within the batch.\r\n If the query text is locked, a special timeout message will be sent, in the following format:\r\n <timeout_exceeded />\r\n If an error occurs, an error message will be sent, in the following format:\r\n <error message=\"message\" />\r\n\r\nFormatted/Non: [query_plan] [xml] NULL\r\n (Requires @get_plans option)\r\n Shows the query plan for the request, if available.\r\n If the plan is locked, a special timeout message will be sent, in the following format:\r\n <timeout_exceeded />\r\n If an error occurs, an error message will be sent, in the following format:\r\n <error message=\"message\" />\r\n\r\nFormatted/Non: [blocking_session_id] [smallint] NULL\r\n When applicable, shows the blocking SPID\r\n\r\nFormatted: [blocked_session_count] [varchar](30) NULL\r\nNon-Formatted: [blocked_session_count] [smallint] NULL\r\n (Requires @find_block_leaders option)\r\n The total number of SPIDs blocked by this session,\r\n all the way down the blocking chain.\r\n\r\nFormatted: [percent_complete] [varchar](30) NULL\r\nNon-Formatted: [percent_complete] [real] NULL\r\n When applicable, shows the percent complete (e.g. for backups, restores, and some rollbacks)\r\n\r\nFormatted/Non: [host_name] [sysname] NOT NULL\r\n Shows the host name for the connection\r\n\r\nFormatted/Non: [login_name] [sysname] NOT NULL\r\n Shows the login name for the connection\r\n\r\nFormatted/Non: [database_name] [sysname] NULL\r\n Shows the connected database\r\n\r\nFormatted/Non: [program_name] [sysname] NULL\r\n Shows the reported program/application name\r\n\r\nFormatted/Non: [additional_info] [xml] NULL\r\n (Requires @get_additional_info option)\r\n Returns additional non-performance-related session/request information\r\n If the script finds a SQL Agent job running, the name of the job and job step will be reported\r\n If @get_task_info = 2 and the script finds a lock wait, the locked object will be reported\r\n\r\nFormatted/Non: [start_time] [datetime] NOT NULL\r\n For active requests, shows the time the request started\r\n For sleeping sessions, shows the time the last batch completed\r\n\r\nFormatted/Non: [login_time] [datetime] NOT NULL\r\n Shows the time that the session connected\r\n\r\nFormatted/Non: [request_id] [int] NULL\r\n For active requests, shows the request_id\r\n Should be 0 unless MARS is being used\r\n\r\nFormatted/Non: [collection_time] [datetime] NOT NULL\r\n Time that this script's final SELECT ran\r\n\r\nFormatted/Non: [memory_info] [xml] NULL\r\n (Requires @get_memory_info)\r\n For active queries that require workspace memory, returns information on memory grants,\r\n resource semaphores, and the resource governor settings that are impacting the allocation.\r\n*/\r\nAS\r\nBEGIN;\r\n SET NOCOUNT ON;\r\n SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;\r\n SET QUOTED_IDENTIFIER ON;\r\n SET ANSI_PADDING ON;\r\n SET CONCAT_NULL_YIELDS_NULL ON;\r\n SET ANSI_WARNINGS ON;\r\n SET NUMERIC_ROUNDABORT OFF;\r\n SET ARITHABORT ON;\r\n\r\n IF\r\n @filter IS NULL\r\n OR @filter_type IS NULL\r\n OR @not_filter IS NULL\r\n OR @not_filter_type IS NULL\r\n OR @show_own_spid IS NULL\r\n OR @show_system_spids IS NULL\r\n OR @show_sleeping_spids IS NULL\r\n OR @get_full_inner_text IS NULL\r\n OR @get_plans IS NULL\r\n OR @get_outer_command IS NULL\r\n OR @get_transaction_info IS NULL\r\n OR @get_task_info IS NULL\r\n OR @get_locks IS NULL\r\n OR @get_avg_time IS NULL\r\n OR @get_additional_info IS NULL\r\n OR @find_block_leaders IS NULL\r\n OR @delta_interval IS NULL\r\n OR @format_output IS NULL\r\n OR @output_column_list IS NULL\r\n OR @sort_order IS NULL\r\n OR @return_schema IS NULL\r\n OR @destination_table IS NULL\r\n OR @help IS NULL\r\n BEGIN;\r\n RAISERROR('Input parameters cannot be NULL', 16, 1);\r\n RETURN;\r\n END;\r\n \r\n IF @filter_type NOT IN ('session', 'program', 'database', 'login', 'host')\r\n BEGIN;\r\n RAISERROR('Valid filter types are: session, program, database, login, host', 16, 1);\r\n RETURN;\r\n END;\r\n \r\n IF @filter_type = 'session' AND @filter LIKE '%[^0123456789]%'\r\n BEGIN;\r\n RAISERROR('Session filters must be valid integers', 16, 1);\r\n RETURN;\r\n END;\r\n \r\n IF @not_filter_type NOT IN ('session', 'program', 'database', 'login', 'host')\r\n BEGIN;\r\n RAISERROR('Valid filter types are: session, program, database, login, host', 16, 1);\r\n RETURN;\r\n END;\r\n \r\n IF @not_filter_type = 'session' AND @not_filter LIKE '%[^0123456789]%'\r\n BEGIN;\r\n RAISERROR('Session filters must be valid integers', 16, 1);\r\n RETURN;\r\n END;\r\n \r\n IF @show_sleeping_spids NOT IN (0, 1, 2)\r\n BEGIN;\r\n RAISERROR('Valid values for @show_sleeping_spids are: 0, 1, or 2', 16, 1);\r\n RETURN;\r\n END;\r\n \r\n IF @get_plans NOT IN (0, 1, 2)\r\n BEGIN;\r\n RAISERROR('Valid values for @get_plans are: 0, 1, or 2', 16, 1);\r\n RETURN;\r\n END;\r\n\r\n IF @get_task_info NOT IN (0, 1, 2)\r\n BEGIN;\r\n RAISERROR('Valid values for @get_task_info are: 0, 1, or 2', 16, 1);\r\n RETURN;\r\n END;\r\n\r\n IF @format_output NOT IN (0, 1, 2)\r\n BEGIN;\r\n RAISERROR('Valid values for @format_output are: 0, 1, or 2', 16, 1);\r\n RETURN;\r\n END;\r\n\r\n IF @get_memory_info = 1 AND NOT EXISTS (SELECT * FROM sys.all_objects WHERE name = 'resource_governor_resource_pools')\r\n BEGIN;\r\n RAISERROR('@get_memory_info is not available for SQL Server 2005.', 16, 1);\r\n RETURN;\r\n END;\r\n\r\n IF @help = 1\r\n BEGIN;\r\n DECLARE\r\n @header VARCHAR(MAX),\r\n @params VARCHAR(MAX),\r\n @outputs VARCHAR(MAX);\r\n\r\n SELECT\r\n @header =\r\n REPLACE\r\n (\r\n REPLACE\r\n (\r\n CONVERT\r\n (\r\n VARCHAR(MAX),\r\n SUBSTRING\r\n (\r\n t.text,\r\n CHARINDEX('/' + REPLICATE('*', 93), t.text) + 94,\r\n CHARINDEX(REPLICATE('*', 93) + '/', t.text) - (CHARINDEX('/' + REPLICATE('*', 93), t.text) + 94)\r\n )\r\n ),\r\n CHAR(13)+CHAR(10),\r\n CHAR(13)\r\n ),\r\n ' ',\r\n ''\r\n ),\r\n @params =\r\n CHAR(13) +\r\n REPLACE\r\n (\r\n REPLACE\r\n (\r\n CONVERT\r\n (\r\n VARCHAR(MAX),\r\n SUBSTRING\r\n (\r\n t.text,\r\n CHARINDEX('--~', t.text) + 5,\r\n CHARINDEX('--~', t.text, CHARINDEX('--~', t.text) + 5) - (CHARINDEX('--~', t.text) + 5)\r\n )\r\n ),\r\n CHAR(13)+CHAR(10),\r\n CHAR(13)\r\n ),\r\n ' ',\r\n ''\r\n ),\r\n @outputs =\r\n CHAR(13) +\r\n REPLACE\r\n (\r\n REPLACE\r\n (\r\n REPLACE\r\n (\r\n CONVERT\r\n (\r\n VARCHAR(MAX),\r\n SUBSTRING\r\n (\r\n t.text,\r\n CHARINDEX('OUTPUT COLUMNS'+CHAR(13)+CHAR(10)+'--------------', t.text) + 32,\r\n CHARINDEX('*/', t.text, CHARINDEX('OUTPUT COLUMNS'+CHAR(13)+CHAR(10)+'--------------', t.text) + 32) - (CHARINDEX('OUTPUT COLUMNS'+CHAR(13)+CHAR(10)+'--------------', t.text) + 32)\r\n )\r\n ),\r\n ' ',\r\n CHAR(255)\r\n ),\r\n CHAR(13)+CHAR(10),\r\n CHAR(13)\r\n ),\r\n ' ',\r\n ''\r\n ) +\r\n CHAR(13)\r\n FROM sys.dm_exec_requests AS r\r\n CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) AS t\r\n WHERE\r\n r.session_id = @@SPID;\r\n\r\n WITH\r\n a0 AS\r\n (SELECT 1 AS n UNION ALL SELECT 1),\r\n a1 AS\r\n (SELECT 1 AS n FROM a0 AS a CROSS JOIN a0 AS b),\r\n a2 AS\r\n (SELECT 1 AS n FROM a1 AS a CROSS JOIN a1 AS b),\r\n a3 AS\r\n (SELECT 1 AS n FROM a2 AS a CROSS JOIN a2 AS b),\r\n a4 AS\r\n (SELECT 1 AS n FROM a3 AS a CROSS JOIN a3 AS b),\r\n numbers AS\r\n (\r\n SELECT TOP(LEN(@header) - 1)\r\n ROW_NUMBER() OVER\r\n (\r\n ORDER BY (SELECT NULL)\r\n ) AS number\r\n FROM a4\r\n ORDER BY\r\n number\r\n )\r\n SELECT\r\n RTRIM(LTRIM(\r\n SUBSTRING\r\n (\r\n @header,\r\n number + 1,\r\n CHARINDEX(CHAR(13), @header, number + 1) - number - 1\r\n )\r\n )) AS [------header---------------------------------------------------------------------------------------------------------------]\r\n FROM numbers\r\n WHERE\r\n SUBSTRING(@header, number, 1) = CHAR(13);\r\n\r\n WITH\r\n a0 AS\r\n (SELECT 1 AS n UNION ALL SELECT 1),\r\n a1 AS\r\n (SELECT 1 AS n FROM a0 AS a CROSS JOIN a0 AS b),\r\n a2 AS\r\n (SELECT 1 AS n FROM a1 AS a CROSS JOIN a1 AS b),\r\n a3 AS\r\n (SELECT 1 AS n FROM a2 AS a CROSS JOIN a2 AS b),\r\n a4 AS\r\n (SELECT 1 AS n FROM a3 AS a CROSS JOIN a3 AS b),\r\n numbers AS\r\n (\r\n SELECT TOP(LEN(@params) - 1)\r\n ROW_NUMBER() OVER\r\n (\r\n ORDER BY (SELECT NULL)\r\n ) AS number\r\n FROM a4\r\n ORDER BY\r\n number\r\n ),\r\n tokens AS\r\n (\r\n SELECT\r\n RTRIM(LTRIM(\r\n SUBSTRING\r\n (\r\n @params,\r\n number + 1,\r\n CHARINDEX(CHAR(13), @params, number + 1) - number - 1\r\n )\r\n )) AS token,\r\n number,\r\n CASE\r\n WHEN SUBSTRING(@params, number + 1, 1) = CHAR(13) THEN number\r\n ELSE COALESCE(NULLIF(CHARINDEX(',' + CHAR(13) + CHAR(13), @params, number), 0), LEN(@params))\r\n END AS param_group,\r\n ROW_NUMBER() OVER\r\n (\r\n PARTITION BY\r\n CHARINDEX(',' + CHAR(13) + CHAR(13), @params, number),\r\n SUBSTRING(@params, number+1, 1)\r\n ORDER BY\r\n number\r\n ) AS group_order\r\n FROM numbers\r\n WHERE\r\n SUBSTRING(@params, number, 1) = CHAR(13)\r\n ),\r\n parsed_tokens AS\r\n (\r\n SELECT\r\n MIN\r\n (\r\n CASE\r\n WHEN token LIKE '@%' THEN token\r\n ELSE NULL\r\n END\r\n ) AS parameter,\r\n MIN\r\n (\r\n CASE\r\n WHEN token LIKE '--%' THEN RIGHT(token, LEN(token) - 2)\r\n ELSE NULL\r\n END\r\n ) AS description,\r\n param_group,\r\n group_order\r\n FROM tokens\r\n WHERE\r\n NOT\r\n (\r\n token = ''\r\n AND group_order > 1\r\n )\r\n GROUP BY\r\n param_group,\r\n group_order\r\n )\r\n SELECT\r\n CASE\r\n WHEN description IS NULL AND parameter IS NULL THEN '-------------------------------------------------------------------------'\r\n WHEN param_group = MAX(param_group) OVER() THEN parameter\r\n ELSE COALESCE(LEFT(parameter, LEN(parameter) - 1), '')\r\n END AS [------parameter----------------------------------------------------------],\r\n CASE\r\n WHEN description IS NULL AND parameter IS NULL THEN '----------------------------------------------------------------------------------------------------------------------'\r\n ELSE COALESCE(description, '')\r\n END AS [------description-----------------------------------------------------------------------------------------------------]\r\n FROM parsed_tokens\r\n ORDER BY\r\n param_group,\r\n group_order;\r\n \r\n WITH\r\n a0 AS\r\n (SELECT 1 AS n UNION ALL SELECT 1),\r\n a1 AS\r\n (SELECT 1 AS n FROM a0 AS a CROSS JOIN a0 AS b),\r\n a2 AS\r\n (SELECT 1 AS n FROM a1 AS a CROSS JOIN a1 AS b),\r\n a3 AS\r\n (SELECT 1 AS n FROM a2 AS a CROSS JOIN a2 AS b),\r\n a4 AS\r\n (SELECT 1 AS n FROM a3 AS a CROSS JOIN a3 AS b),\r\n numbers AS\r\n (\r\n SELECT TOP(LEN(@outputs) - 1)\r\n ROW_NUMBER() OVER\r\n (\r\n ORDER BY (SELECT NULL)\r\n ) AS number\r\n FROM a4\r\n ORDER BY\r\n number\r\n ),\r\n tokens AS\r\n (\r\n SELECT\r\n RTRIM(LTRIM(\r\n SUBSTRING\r\n (\r\n @outputs,\r\n number + 1,\r\n CASE\r\n WHEN\r\n COALESCE(NULLIF(CHARINDEX(CHAR(13) + 'Formatted', @outputs, number + 1), 0), LEN(@outputs)) <\r\n COALESCE(NULLIF(CHARINDEX(CHAR(13) + CHAR(255) COLLATE Latin1_General_Bin2, @outputs, number + 1), 0), LEN(@outputs))\r\n THEN COALESCE(NULLIF(CHARINDEX(CHAR(13) + 'Formatted', @outputs, number + 1), 0), LEN(@outputs)) - number - 1\r\n ELSE\r\n COALESCE(NULLIF(CHARINDEX(CHAR(13) + CHAR(255) COLLATE Latin1_General_Bin2, @outputs, number + 1), 0), LEN(@outputs)) - number - 1\r\n END\r\n )\r\n )) AS token,\r\n number,\r\n COALESCE(NULLIF(CHARINDEX(CHAR(13) + 'Formatted', @outputs, number + 1), 0), LEN(@outputs)) AS output_group,\r\n ROW_NUMBER() OVER\r\n (\r\n PARTITION BY\r\n COALESCE(NULLIF(CHARINDEX(CHAR(13) + 'Formatted', @outputs, number + 1), 0), LEN(@outputs))\r\n ORDER BY\r\n number\r\n ) AS output_group_order\r\n FROM numbers\r\n WHERE\r\n SUBSTRING(@outputs, number, 10) = CHAR(13) + 'Formatted'\r\n OR SUBSTRING(@outputs, number, 2) = CHAR(13) + CHAR(255) COLLATE Latin1_General_Bin2\r\n ),\r\n output_tokens AS\r\n (\r\n SELECT\r\n *,\r\n CASE output_group_order\r\n WHEN 2 THEN MAX(CASE output_group_order WHEN 1 THEN token ELSE NULL END) OVER (PARTITION BY output_group)\r\n ELSE ''\r\n END COLLATE Latin1_General_Bin2 AS column_info\r\n FROM tokens\r\n )\r\n SELECT\r\n CASE output_group_order\r\n WHEN 1 THEN '-----------------------------------'\r\n WHEN 2 THEN\r\n CASE\r\n WHEN CHARINDEX('Formatted/Non:', column_info) = 1 THEN\r\n SUBSTRING(column_info, CHARINDEX(CHAR(255) COLLATE Latin1_General_Bin2, column_info)+1, CHARINDEX(']', column_info, CHARINDEX(CHAR(255) COLLATE Latin1_General_Bin2, column_info)+2) - CHARINDEX(CHAR(255) COLLATE Latin1_General_Bin2, column_info))\r\n ELSE\r\n SUBSTRING(column_info, CHARINDEX(CHAR(255) COLLATE Latin1_General_Bin2, column_info)+2, CHARINDEX(']', column_info, CHARINDEX(CHAR(255) COLLATE Latin1_General_Bin2, column_info)+2) - CHARINDEX(CHAR(255) COLLATE Latin1_General_Bin2, column_info)-1)\r\n END\r\n ELSE ''\r\n END AS formatted_column_name,\r\n CASE output_group_order\r\n WHEN 1 THEN '-----------------------------------'\r\n WHEN 2 THEN\r\n CASE\r\n WHEN CHARINDEX('Formatted/Non:', column_info) = 1 THEN\r\n SUBSTRING(column_info, CHARINDEX(']', column_info)+2, LEN(column_info))\r\n ELSE\r\n SUBSTRING(column_info, CHARINDEX(']', column_info)+2, CHARINDEX('Non-Formatted:', column_info, CHARINDEX(']', column_info)+2) - CHARINDEX(']', column_info)-3)\r\n END\r\n ELSE ''\r\n END AS formatted_column_type,\r\n CASE output_group_order\r\n WHEN 1 THEN '---------------------------------------'\r\n WHEN 2 THEN\r\n CASE\r\n WHEN CHARINDEX('Formatted/Non:', column_info) = 1 THEN ''\r\n ELSE\r\n CASE\r\n WHEN SUBSTRING(column_info, CHARINDEX(CHAR(255) COLLATE Latin1_General_Bin2, column_info, CHARINDEX('Non-Formatted:', column_info))+1, 1) = '<' THEN\r\n SUBSTRING(column_info, CHARINDEX(CHAR(255) COLLATE Latin1_General_Bin2, column_info, CHARINDEX('Non-Formatted:', column_info))+1, CHARINDEX('>', column_info, CHARINDEX(CHAR(255) COLLATE Latin1_General_Bin2, column_info, CHARINDEX('Non-Formatted:', column_info))+1) - CHARINDEX(CHAR(255) COLLATE Latin1_General_Bin2, column_info, CHARINDEX('Non-Formatted:', column_info)))\r\n ELSE\r\n SUBSTRING(column_info, CHARINDEX(CHAR(255) COLLATE Latin1_General_Bin2, column_info, CHARINDEX('Non-Formatted:', column_info))+1, CHARINDEX(']', column_info, CHARINDEX(CHAR(255) COLLATE Latin1_General_Bin2, column_info, CHARINDEX('Non-Formatted:', column_info))+1) - CHARINDEX(CHAR(255) COLLATE Latin1_General_Bin2, column_info, CHARINDEX('Non-Formatted:', column_info)))\r\n END\r\n END\r\n ELSE ''\r\n END AS unformatted_column_name,\r\n CASE output_group_order\r\n WHEN 1 THEN '---------------------------------------'\r\n WHEN 2 THEN\r\n CASE\r\n WHEN CHARINDEX('Formatted/Non:', column_info) = 1 THEN ''\r\n ELSE\r\n CASE\r\n WHEN SUBSTRING(column_info, CHARINDEX(CHAR(255) COLLATE Latin1_General_Bin2, column_info, CHARINDEX('Non-Formatted:', column_info))+1, 1) = '<' THEN ''\r\n ELSE\r\n SUBSTRING(column_info, CHARINDEX(']', column_info, CHARINDEX('Non-Formatted:', column_info))+2, CHARINDEX('Non-Formatted:', column_info, CHARINDEX(']', column_info)+2) - CHARINDEX(']', column_info)-3)\r\n END\r\n END\r\n ELSE ''\r\n END AS unformatted_column_type,\r\n CASE output_group_order\r\n WHEN 1 THEN '----------------------------------------------------------------------------------------------------------------------'\r\n ELSE REPLACE(token, CHAR(255) COLLATE Latin1_General_Bin2, '')\r\n END AS [------description-----------------------------------------------------------------------------------------------------]\r\n FROM output_tokens\r\n WHERE\r\n NOT\r\n (\r\n output_group_order = 1\r\n AND output_group = LEN(@outputs)\r\n )\r\n ORDER BY\r\n output_group,\r\n CASE output_group_order\r\n WHEN 1 THEN 99\r\n ELSE output_group_order\r\n END;\r\n\r\n RETURN;\r\n END;\r\n\r\n WITH\r\n a0 AS\r\n (SELECT 1 AS n UNION ALL SELECT 1),\r\n a1 AS\r\n (SELECT 1 AS n FROM a0 AS a CROSS JOIN a0 AS b),\r\n a2 AS\r\n (SELECT 1 AS n FROM a1 AS a CROSS JOIN a1 AS b),\r\n a3 AS\r\n (SELECT 1 AS n FROM a2 AS a CROSS JOIN a2 AS b),\r\n a4 AS\r\n (SELECT 1 AS n FROM a3 AS a CROSS JOIN a3 AS b),\r\n numbers AS\r\n (\r\n SELECT TOP(LEN(@output_column_list))\r\n ROW_NUMBER() OVER\r\n (\r\n ORDER BY (SELECT NULL)\r\n ) AS number\r\n FROM a4\r\n ORDER BY\r\n number\r\n ),\r\n tokens AS\r\n (\r\n SELECT\r\n '|[' +\r\n SUBSTRING\r\n (\r\n @output_column_list,\r\n number + 1,\r\n CHARINDEX(']', @output_column_list, number) - number - 1\r\n ) + '|]' AS token,\r\n number\r\n FROM numbers\r\n WHERE\r\n SUBSTRING(@output_column_list, number, 1) = '['\r\n ),\r\n ordered_columns AS\r\n (\r\n SELECT\r\n x.column_name,\r\n ROW_NUMBER() OVER\r\n (\r\n PARTITION BY\r\n x.column_name\r\n ORDER BY\r\n tokens.number,\r\n x.default_order\r\n ) AS r,\r\n ROW_NUMBER() OVER\r\n (\r\n ORDER BY\r\n tokens.number,\r\n x.default_order\r\n ) AS s\r\n FROM tokens\r\n JOIN\r\n (\r\n SELECT '[session_id]' AS column_name, 1 AS default_order\r\n UNION ALL\r\n SELECT '[dd hh:mm:ss.mss]', 2\r\n WHERE\r\n @format_output IN (1, 2)\r\n UNION ALL\r\n SELECT '[dd hh:mm:ss.mss (avg)]', 3\r\n WHERE\r\n @format_output IN (1, 2)\r\n AND @get_avg_time = 1\r\n UNION ALL\r\n SELECT '[avg_elapsed_time]', 4\r\n WHERE\r\n @format_output = 0\r\n AND @get_avg_time = 1\r\n UNION ALL\r\n SELECT '[physical_io]', 5\r\n WHERE\r\n @get_task_info = 2\r\n UNION ALL\r\n SELECT '[reads]', 6\r\n UNION ALL\r\n SELECT '[physical_reads]', 7\r\n UNION ALL\r\n SELECT '[writes]', 8\r\n UNION ALL\r\n SELECT '[tempdb_allocations]', 9\r\n UNION ALL\r\n SELECT '[tempdb_current]', 10\r\n UNION ALL\r\n SELECT '[CPU]', 11\r\n UNION ALL\r\n SELECT '[context_switches]', 12\r\n WHERE\r\n @get_task_info = 2\r\n UNION ALL\r\n SELECT '[used_memory]', 13\r\n UNION ALL\r\n SELECT '[max_used_memory]', 14\r\n WHERE\r\n @get_memory_info = 1\r\n UNION ALL\r\n SELECT '[requested_memory]', 15\r\n WHERE\r\n @get_memory_info = 1\r\n UNION ALL\r\n SELECT '[granted_memory]', 16\r\n WHERE\r\n @get_memory_info = 1\r\n UNION ALL\r\n SELECT '[physical_io_delta]', 17\r\n WHERE\r\n @delta_interval > 0 \r\n AND @get_task_info = 2\r\n UNION ALL\r\n SELECT '[reads_delta]', 18\r\n WHERE\r\n @delta_interval > 0\r\n UNION ALL\r\n SELECT '[physical_reads_delta]', 19\r\n WHERE\r\n @delta_interval > 0\r\n UNION ALL\r\n SELECT '[writes_delta]', 20\r\n WHERE\r\n @delta_interval > 0\r\n UNION ALL\r\n SELECT '[tempdb_allocations_delta]', 21\r\n WHERE\r\n @delta_interval > 0\r\n UNION ALL\r\n SELECT '[tempdb_current_delta]', 22\r\n WHERE\r\n @delta_interval > 0\r\n UNION ALL\r\n SELECT '[CPU_delta]', 23\r\n WHERE\r\n @delta_interval > 0\r\n UNION ALL\r\n SELECT '[context_switches_delta]', 24\r\n WHERE\r\n @delta_interval > 0\r\n AND @get_task_info = 2\r\n UNION ALL\r\n SELECT '[used_memory_delta]', 25\r\n WHERE\r\n @delta_interval > 0\r\n UNION ALL\r\n SELECT '[max_used_memory_delta]', 26\r\n WHERE\r\n @delta_interval > 0\r\n AND @get_memory_info = 1\r\n UNION ALL\r\n SELECT '[tasks]', 27\r\n WHERE\r\n @get_task_info = 2\r\n UNION ALL\r\n SELECT '[status]', 28\r\n UNION ALL\r\n SELECT '[wait_info]', 29\r\n WHERE\r\n @get_task_info > 0\r\n OR @find_block_leaders = 1\r\n UNION ALL\r\n SELECT '[locks]', 30\r\n WHERE\r\n @get_locks = 1\r\n UNION ALL\r\n SELECT '[tran_start_time]', 31\r\n WHERE\r\n @get_transaction_info = 1\r\n UNION ALL\r\n SELECT '[tran_log_writes]', 32\r\n WHERE\r\n @get_transaction_info = 1\r\n UNION ALL\r\n SELECT '[implicit_tran]', 33\r\n WHERE\r\n @get_transaction_info = 1\r\n UNION ALL\r\n SELECT '[open_tran_count]', 34\r\n UNION ALL\r\n SELECT '[sql_command]', 35\r\n WHERE\r\n @get_outer_command = 1\r\n UNION ALL\r\n SELECT '[sql_text]', 36\r\n UNION ALL\r\n SELECT '[query_plan]', 37\r\n WHERE\r\n @get_plans >= 1\r\n UNION ALL\r\n SELECT '[blocking_session_id]', 38\r\n WHERE\r\n @get_task_info > 0\r\n OR @find_block_leaders = 1\r\n UNION ALL\r\n SELECT '[blocked_session_count]', 39\r\n WHERE\r\n @find_block_leaders = 1\r\n UNION ALL\r\n SELECT '[percent_complete]', 40\r\n UNION ALL\r\n SELECT '[host_name]', 41\r\n UNION ALL\r\n SELECT '[login_name]', 42\r\n UNION ALL\r\n SELECT '[database_name]', 43\r\n UNION ALL\r\n SELECT '[program_name]', 44\r\n UNION ALL\r\n SELECT '[additional_info]', 45\r\n WHERE\r\n @get_additional_info = 1\r\n UNION ALL\r\n SELECT '[memory_info]', 46\r\n WHERE\r\n @get_memory_info = 1\r\n UNION ALL\r\n SELECT '[start_time]', 47\r\n UNION ALL\r\n SELECT '[login_time]', 48\r\n UNION ALL\r\n SELECT '[request_id]', 49\r\n UNION ALL\r\n SELECT '[collection_time]', 50\r\n ) AS x ON\r\n x.column_name LIKE token ESCAPE '|'\r\n )\r\n SELECT\r\n @output_column_list =\r\n STUFF\r\n (\r\n (\r\n SELECT\r\n ',' + column_name as [text()]\r\n FROM ordered_columns\r\n WHERE\r\n r = 1\r\n ORDER BY\r\n s\r\n FOR XML\r\n PATH('')\r\n ),\r\n 1,\r\n 1,\r\n ''\r\n );\r\n \r\n IF COALESCE(RTRIM(@output_column_list), '') = ''\r\n BEGIN;\r\n RAISERROR('No valid column matches found in @output_column_list or no columns remain due to selected options.', 16, 1);\r\n RETURN;\r\n END;\r\n \r\n IF @destination_table <> ''\r\n BEGIN;\r\n SET @destination_table =\r\n --database\r\n COALESCE(QUOTENAME(PARSENAME(@destination_table, 3)) + '.', '') +\r\n --schema\r\n COALESCE(QUOTENAME(PARSENAME(@destination_table, 2)) + '.', '') +\r\n --table\r\n COALESCE(QUOTENAME(PARSENAME(@destination_table, 1)), '');\r\n \r\n IF COALESCE(RTRIM(@destination_table), '') = ''\r\n BEGIN;\r\n RAISERROR('Destination table not properly formatted.', 16, 1);\r\n RETURN;\r\n END;\r\n END;\r\n\r\n WITH\r\n a0 AS\r\n (SELECT 1 AS n UNION ALL SELECT 1),\r\n a1 AS\r\n (SELECT 1 AS n FROM a0 AS a CROSS JOIN a0 AS b),\r\n a2 AS\r\n (SELECT 1 AS n FROM a1 AS a CROSS JOIN a1 AS b),\r\n a3 AS\r\n (SELECT 1 AS n FROM a2 AS a CROSS JOIN a2 AS b),\r\n a4 AS\r\n (SELECT 1 AS n FROM a3 AS a CROSS JOIN a3 AS b),\r\n numbers AS\r\n (\r\n SELECT TOP(LEN(@sort_order))\r\n ROW_NUMBER() OVER\r\n (\r\n ORDER BY (SELECT NULL)\r\n ) AS number\r\n FROM a4\r\n ORDER BY\r\n number\r\n ),\r\n tokens AS\r\n (\r\n SELECT\r\n '|[' +\r\n SUBSTRING\r\n (\r\n @sort_order,\r\n number + 1,\r\n CHARINDEX(']', @sort_order, number) - number - 1\r\n ) + '|]' AS token,\r\n SUBSTRING\r\n (\r\n @sort_order,\r\n CHARINDEX(']', @sort_order, number) + 1,\r\n COALESCE(NULLIF(CHARINDEX('[', @sort_order, CHARINDEX(']', @sort_order, number)), 0), LEN(@sort_order)) - CHARINDEX(']', @sort_order, number)\r\n ) AS next_chunk,\r\n number\r\n FROM numbers\r\n WHERE\r\n SUBSTRING(@sort_order, number, 1) = '['\r\n ),\r\n ordered_columns AS\r\n (\r\n SELECT\r\n x.column_name +\r\n CASE\r\n WHEN LOWER(tokens.next_chunk) LIKE '%asc%' THEN ' ASC'\r\n WHEN LOWER(tokens.next_chunk) LIKE '%desc%' THEN ' DESC'\r\n ELSE ''\r\n END AS column_name,\r\n ROW_NUMBER() OVER\r\n (\r\n PARTITION BY\r\n x.column_name\r\n ORDER BY\r\n tokens.number\r\n ) AS r,\r\n tokens.number\r\n FROM tokens\r\n JOIN\r\n (\r\n SELECT '[session_id]' AS column_name\r\n UNION ALL\r\n SELECT '[physical_io]'\r\n UNION ALL\r\n SELECT '[reads]'\r\n UNION ALL\r\n SELECT '[physical_reads]'\r\n UNION ALL\r\n SELECT '[writes]'\r\n UNION ALL\r\n SELECT '[tempdb_allocations]'\r\n UNION ALL\r\n SELECT '[tempdb_current]'\r\n UNION ALL\r\n SELECT '[CPU]'\r\n UNION ALL\r\n SELECT '[context_switches]'\r\n UNION ALL\r\n SELECT '[used_memory]'\r\n UNION ALL\r\n SELECT '[max_used_memory]'\r\n UNION ALL\r\n SELECT '[requested_memory]'\r\n UNION ALL\r\n SELECT '[granted_memory]'\r\n UNION ALL\r\n SELECT '[physical_io_delta]'\r\n UNION ALL\r\n SELECT '[reads_delta]'\r\n UNION ALL\r\n SELECT '[physical_reads_delta]'\r\n UNION ALL\r\n SELECT '[writes_delta]'\r\n UNION ALL\r\n SELECT '[tempdb_allocations_delta]'\r\n UNION ALL\r\n SELECT '[tempdb_current_delta]'\r\n UNION ALL\r\n SELECT '[CPU_delta]'\r\n UNION ALL\r\n SELECT '[context_switches_delta]'\r\n UNION ALL\r\n SELECT '[used_memory_delta]'\r\n UNION ALL\r\n SELECT '[max_used_memory_delta]'\r\n UNION ALL\r\n SELECT '[tasks]'\r\n UNION ALL\r\n SELECT '[tran_start_time]'\r\n UNION ALL\r\n SELECT '[open_tran_count]'\r\n UNION ALL\r\n SELECT '[blocking_session_id]'\r\n UNION ALL\r\n SELECT '[blocked_session_count]'\r\n UNION ALL\r\n SELECT '[percent_complete]'\r\n UNION ALL\r\n SELECT '[host_name]'\r\n UNION ALL\r\n SELECT '[login_name]'\r\n UNION ALL\r\n SELECT '[database_name]'\r\n UNION ALL\r\n SELECT '[start_time]'\r\n UNION ALL\r\n SELECT '[login_time]'\r\n UNION ALL\r\n SELECT '[program_name]'\r\n ) AS x ON\r\n x.column_name LIKE token ESCAPE '|'\r\n )\r\n SELECT\r\n @sort_order = COALESCE(z.sort_order, '')\r\n FROM\r\n (\r\n SELECT\r\n STUFF\r\n (\r\n (\r\n SELECT\r\n ',' + column_name as [text()]\r\n FROM ordered_columns\r\n WHERE\r\n r = 1\r\n ORDER BY\r\n number\r\n FOR XML\r\n PATH('')\r\n ),\r\n 1,\r\n 1,\r\n ''\r\n ) AS sort_order\r\n ) AS z;\r\n\r\n CREATE TABLE #sessions\r\n (\r\n recursion SMALLINT NOT NULL,\r\n session_id SMALLINT NOT NULL,\r\n request_id INT NOT NULL,\r\n session_number INT NOT NULL,\r\n elapsed_time INT NOT NULL,\r\n avg_elapsed_time INT NULL,\r\n physical_io BIGINT NULL,\r\n reads BIGINT NULL,\r\n physical_reads BIGINT NULL,\r\n writes BIGINT NULL,\r\n tempdb_allocations BIGINT NULL,\r\n tempdb_current BIGINT NULL,\r\n CPU BIGINT NULL,\r\n thread_CPU_snapshot BIGINT NULL,\r\n context_switches BIGINT NULL,\r\n used_memory BIGINT NOT NULL,\r\n max_used_memory BIGINT NULL,\r\n requested_memory BIGINT NULL,\r\n granted_memory BIGINT NULL,\r\n tasks SMALLINT NULL,\r\n status VARCHAR(30) NOT NULL,\r\n wait_info NVARCHAR(4000) NULL,\r\n locks XML NULL,\r\n transaction_id BIGINT NULL,\r\n tran_start_time DATETIME NULL,\r\n tran_log_writes NVARCHAR(4000) NULL,\r\n implicit_tran NVARCHAR(3) NULL,\r\n open_tran_count SMALLINT NULL,\r\n sql_command XML NULL,\r\n sql_handle VARBINARY(64) NULL,\r\n statement_start_offset INT NULL,\r\n statement_end_offset INT NULL,\r\n sql_text XML NULL,\r\n plan_handle VARBINARY(64) NULL,\r\n query_plan XML NULL,\r\n blocking_session_id SMALLINT NULL,\r\n blocked_session_count SMALLINT NULL,\r\n percent_complete REAL NULL,\r\n host_name sysname NULL,\r\n login_name sysname NOT NULL,\r\n database_name sysname NULL,\r\n program_name sysname NULL,\r\n additional_info XML NULL,\r\n memory_info XML NULL,\r\n start_time DATETIME NOT NULL,\r\n login_time DATETIME NULL,\r\n last_request_start_time DATETIME NULL,\r\n PRIMARY KEY CLUSTERED (session_id, request_id, recursion) WITH (IGNORE_DUP_KEY = ON),\r\n UNIQUE NONCLUSTERED (transaction_id, session_id, request_id, recursion) WITH (IGNORE_DUP_KEY = ON)\r\n );\r\n\r\n IF @return_schema = 0\r\n BEGIN;\r\n --Disable unnecessary autostats on the table\r\n CREATE STATISTICS s_session_id ON #sessions (session_id)\r\n WITH SAMPLE 0 ROWS, NORECOMPUTE;\r\n CREATE STATISTICS s_request_id ON #sessions (request_id)\r\n WITH SAMPLE 0 ROWS, NORECOMPUTE;\r\n CREATE STATISTICS s_transaction_id ON #sessions (transaction_id)\r\n WITH SAMPLE 0 ROWS, NORECOMPUTE;\r\n CREATE STATISTICS s_session_number ON #sessions (session_number)\r\n WITH SAMPLE 0 ROWS, NORECOMPUTE;\r\n CREATE STATISTICS s_status ON #sessions (status)\r\n WITH SAMPLE 0 ROWS, NORECOMPUTE;\r\n CREATE STATISTICS s_start_time ON #sessions (start_time)\r\n WITH SAMPLE 0 ROWS, NORECOMPUTE;\r\n CREATE STATISTICS s_last_request_start_time ON #sessions (last_request_start_time)\r\n WITH SAMPLE 0 ROWS, NORECOMPUTE;\r\n CREATE STATISTICS s_recursion ON #sessions (recursion)\r\n WITH SAMPLE 0 ROWS, NORECOMPUTE;\r\n\r\n DECLARE @recursion SMALLINT;\r\n SET @recursion =\r\n CASE @delta_interval\r\n WHEN 0 THEN 1\r\n ELSE -1\r\n END;\r\n\r\n DECLARE @first_collection_ms_ticks BIGINT;\r\n DECLARE @last_collection_start DATETIME;\r\n DECLARE @sys_info BIT;\r\n SET @sys_info = ISNULL(CONVERT(BIT, SIGN(OBJECT_ID('sys.dm_os_sys_info'))), 0);\r\n\r\n --Used for the delta pull\r\n REDO:;\r\n \r\n IF\r\n @get_locks = 1\r\n AND @recursion = 1\r\n AND @output_column_list LIKE '%|[locks|]%' ESCAPE '|'\r\n BEGIN;\r\n SELECT\r\n y.resource_type,\r\n y.database_name,\r\n y.object_id,\r\n y.file_id,\r\n y.page_type,\r\n y.hobt_id,\r\n y.allocation_unit_id,\r\n y.index_id,\r\n y.schema_id,\r\n y.principal_id,\r\n y.request_mode,\r\n y.request_status,\r\n y.session_id,\r\n y.resource_description,\r\n y.request_count,\r\n s.request_id,\r\n s.start_time,\r\n CONVERT(sysname, NULL) AS object_name,\r\n CONVERT(sysname, NULL) AS index_name,\r\n CONVERT(sysname, NULL) AS schema_name,\r\n CONVERT(sysname, NULL) AS principal_name,\r\n CONVERT(NVARCHAR(2048), NULL) AS query_error\r\n INTO #locks\r\n FROM\r\n (\r\n SELECT\r\n sp.spid AS session_id,\r\n CASE sp.status\r\n WHEN 'sleeping' THEN CONVERT(INT, 0)\r\n ELSE sp.request_id\r\n END AS request_id,\r\n CASE sp.status\r\n WHEN 'sleeping' THEN sp.last_batch\r\n ELSE COALESCE(req.start_time, sp.last_batch)\r\n END AS start_time,\r\n sp.dbid\r\n FROM sys.sysprocesses AS sp\r\n OUTER APPLY\r\n (\r\n SELECT TOP(1)\r\n CASE\r\n WHEN\r\n (\r\n sp.hostprocess > ''\r\n OR r.total_elapsed_time < 0\r\n ) THEN\r\n r.start_time\r\n ELSE\r\n DATEADD\r\n (\r\n ms,\r\n 1000 * (DATEPART(ms, DATEADD(second, -(r.total_elapsed_time / 1000), GETDATE())) / 500) - DATEPART(ms, DATEADD(second, -(r.total_elapsed_time / 1000), GETDATE())),\r\n DATEADD(second, -(r.total_elapsed_time / 1000), GETDATE())\r\n )\r\n END AS start_time\r\n FROM sys.dm_exec_requests AS r\r\n WHERE\r\n r.session_id = sp.spid\r\n AND r.request_id = sp.request_id\r\n ) AS req\r\n WHERE\r\n --Process inclusive filter\r\n 1 =\r\n CASE\r\n WHEN @filter <> '' THEN\r\n CASE @filter_type\r\n WHEN 'session' THEN\r\n CASE\r\n WHEN\r\n CONVERT(SMALLINT, @filter) = 0\r\n OR sp.spid = CONVERT(SMALLINT, @filter)\r\n THEN 1\r\n ELSE 0\r\n END\r\n WHEN 'program' THEN\r\n CASE\r\n WHEN sp.program_name LIKE @filter THEN 1\r\n ELSE 0\r\n END\r\n WHEN 'login' THEN\r\n CASE\r\n WHEN sp.loginame LIKE @filter THEN 1\r\n ELSE 0\r\n END\r\n WHEN 'host' THEN\r\n CASE\r\n WHEN sp.hostname LIKE @filter THEN 1\r\n ELSE 0\r\n END\r\n WHEN 'database' THEN\r\n CASE\r\n WHEN DB_NAME(sp.dbid) LIKE @filter THEN 1\r\n ELSE 0\r\n END\r\n ELSE 0\r\n END\r\n ELSE 1\r\n END\r\n --Process exclusive filter\r\n AND 0 =\r\n CASE\r\n WHEN @not_filter <> '' THEN\r\n CASE @not_filter_type\r\n WHEN 'session' THEN\r\n CASE\r\n WHEN sp.spid = CONVERT(SMALLINT, @not_filter) THEN 1\r\n ELSE 0\r\n END\r\n WHEN 'program' THEN\r\n CASE\r\n WHEN sp.program_name LIKE @not_filter THEN 1\r\n ELSE 0\r\n END\r\n WHEN 'login' THEN\r\n CASE\r\n WHEN sp.loginame LIKE @not_filter THEN 1\r\n ELSE 0\r\n END\r\n WHEN 'host' THEN\r\n CASE\r\n WHEN sp.hostname LIKE @not_filter THEN 1\r\n ELSE 0\r\n END\r\n WHEN 'database' THEN\r\n CASE\r\n WHEN DB_NAME(sp.dbid) LIKE @not_filter THEN 1\r\n ELSE 0\r\n END\r\n ELSE 0\r\n END\r\n ELSE 0\r\n END\r\n AND\r\n (\r\n @show_own_spid = 1\r\n OR sp.spid <> @@SPID\r\n )\r\n AND\r\n (\r\n @show_system_spids = 1\r\n OR sp.hostprocess > ''\r\n )\r\n AND sp.ecid = 0\r\n ) AS s\r\n INNER HASH JOIN\r\n (\r\n SELECT\r\n x.resource_type,\r\n x.database_name,\r\n x.object_id,\r\n x.file_id,\r\n CASE\r\n WHEN x.page_no = 1 OR x.page_no % 8088 = 0 THEN 'PFS'\r\n WHEN x.page_no = 2 OR x.page_no % 511232 = 0 THEN 'GAM'\r\n WHEN x.page_no = 3 OR (x.page_no - 1) % 511232 = 0 THEN 'SGAM'\r\n WHEN x.page_no = 6 OR (x.page_no - 6) % 511232 = 0 THEN 'DCM'\r\n WHEN x.page_no = 7 OR (x.page_no - 7) % 511232 = 0 THEN 'BCM'\r\n WHEN x.page_no IS NOT NULL THEN '*'\r\n ELSE NULL\r\n END AS page_type,\r\n x.hobt_id,\r\n x.allocation_unit_id,\r\n x.index_id,\r\n x.schema_id,\r\n x.principal_id,\r\n x.request_mode,\r\n x.request_status,\r\n x.session_id,\r\n x.request_id,\r\n CASE\r\n WHEN COALESCE(x.object_id, x.file_id, x.hobt_id, x.allocation_unit_id, x.index_id, x.schema_id, x.principal_id) IS NULL THEN NULLIF(resource_description, '')\r\n ELSE NULL\r\n END AS resource_description,\r\n COUNT(*) AS request_count\r\n FROM\r\n (\r\n SELECT\r\n tl.resource_type +\r\n CASE\r\n WHEN tl.resource_subtype = '' THEN ''\r\n ELSE '.' + tl.resource_subtype\r\n END AS resource_type,\r\n COALESCE(DB_NAME(tl.resource_database_id), N'(null)') AS database_name,\r\n CONVERT\r\n (\r\n INT,\r\n CASE\r\n WHEN tl.resource_type = 'OBJECT' THEN tl.resource_associated_entity_id\r\n WHEN tl.resource_description LIKE '%object_id = %' THEN\r\n (\r\n SUBSTRING\r\n (\r\n tl.resource_description,\r\n (CHARINDEX('object_id = ', tl.resource_description) + 12),\r\n COALESCE\r\n (\r\n NULLIF\r\n (\r\n CHARINDEX(',', tl.resource_description, CHARINDEX('object_id = ', tl.resource_description) + 12),\r\n 0\r\n ),\r\n DATALENGTH(tl.resource_description)+1\r\n ) - (CHARINDEX('object_id = ', tl.resource_description) + 12)\r\n )\r\n )\r\n ELSE NULL\r\n END\r\n ) AS object_id,\r\n CONVERT\r\n (\r\n INT,\r\n CASE\r\n WHEN tl.resource_type = 'FILE' THEN CONVERT(INT, tl.resource_description)\r\n WHEN tl.resource_type IN ('PAGE', 'EXTENT', 'RID') THEN LEFT(tl.resource_description, CHARINDEX(':', tl.resource_description)-1)\r\n ELSE NULL\r\n END\r\n ) AS file_id,\r\n CONVERT\r\n (\r\n INT,\r\n CASE\r\n WHEN tl.resource_type IN ('PAGE', 'EXTENT', 'RID') THEN\r\n SUBSTRING\r\n (\r\n tl.resource_description,\r\n CHARINDEX(':', tl.resource_description) + 1,\r\n COALESCE\r\n (\r\n NULLIF\r\n (\r\n CHARINDEX(':', tl.resource_description, CHARINDEX(':', tl.resource_description) + 1),\r\n 0\r\n ),\r\n DATALENGTH(tl.resource_description)+1\r\n ) - (CHARINDEX(':', tl.resource_description) + 1)\r\n )\r\n ELSE NULL\r\n END\r\n ) AS page_no,\r\n CASE\r\n WHEN tl.resource_type IN ('PAGE', 'KEY', 'RID', 'HOBT') THEN tl.resource_associated_entity_id\r\n ELSE NULL\r\n END AS hobt_id,\r\n CASE\r\n WHEN tl.resource_type = 'ALLOCATION_UNIT' THEN tl.resource_associated_entity_id\r\n ELSE NULL\r\n END AS allocation_unit_id,\r\n CONVERT\r\n (\r\n INT,\r\n CASE\r\n WHEN\r\n /*TODO: Deal with server principals*/\r\n tl.resource_subtype <> 'SERVER_PRINCIPAL'\r\n AND tl.resource_description LIKE '%index_id or stats_id = %' THEN\r\n (\r\n SUBSTRING\r\n (\r\n tl.resource_description,\r\n (CHARINDEX('index_id or stats_id = ', tl.resource_description) + 23),\r\n COALESCE\r\n (\r\n NULLIF\r\n (\r\n CHARINDEX(',', tl.resource_description, CHARINDEX('index_id or stats_id = ', tl.resource_description) + 23),\r\n 0\r\n ),\r\n DATALENGTH(tl.resource_description)+1\r\n ) - (CHARINDEX('index_id or stats_id = ', tl.resource_description) + 23)\r\n )\r\n )\r\n ELSE NULL\r\n END\r\n ) AS index_id,\r\n CONVERT\r\n (\r\n INT,\r\n CASE\r\n WHEN tl.resource_description LIKE '%schema_id = %' THEN\r\n (\r\n SUBSTRING\r\n (\r\n tl.resource_description,\r\n (CHARINDEX('schema_id = ', tl.resource_description) + 12),\r\n COALESCE\r\n (\r\n NULLIF\r\n (\r\n CHARINDEX(',', tl.resource_description, CHARINDEX('schema_id = ', tl.resource_description) + 12),\r\n 0\r\n ),\r\n DATALENGTH(tl.resource_description)+1\r\n ) - (CHARINDEX('schema_id = ', tl.resource_description) + 12)\r\n )\r\n )\r\n ELSE NULL\r\n END\r\n ) AS schema_id,\r\n CONVERT\r\n (\r\n INT,\r\n CASE\r\n WHEN tl.resource_description LIKE '%principal_id = %' THEN\r\n (\r\n SUBSTRING\r\n (\r\n tl.resource_description,\r\n (CHARINDEX('principal_id = ', tl.resource_description) + 15),\r\n COALESCE\r\n (\r\n NULLIF\r\n (\r\n CHARINDEX(',', tl.resource_description, CHARINDEX('principal_id = ', tl.resource_description) + 15),\r\n 0\r\n ),\r\n DATALENGTH(tl.resource_description)+1\r\n ) - (CHARINDEX('principal_id = ', tl.resource_description) + 15)\r\n )\r\n )\r\n ELSE NULL\r\n END\r\n ) AS principal_id,\r\n tl.request_mode,\r\n tl.request_status,\r\n tl.request_session_id AS session_id,\r\n tl.request_request_id AS request_id,\r\n\r\n /*TODO: Applocks, other resource_descriptions*/\r\n RTRIM(tl.resource_description) AS resource_description,\r\n tl.resource_associated_entity_id\r\n /*********************************************/\r\n FROM\r\n (\r\n SELECT\r\n request_session_id,\r\n CONVERT(VARCHAR(120), resource_type) COLLATE Latin1_General_Bin2 AS resource_type,\r\n CONVERT(VARCHAR(120), resource_subtype) COLLATE Latin1_General_Bin2 AS resource_subtype,\r\n resource_database_id,\r\n CONVERT(VARCHAR(512), resource_description) COLLATE Latin1_General_Bin2 AS resource_description,\r\n resource_associated_entity_id,\r\n CONVERT(VARCHAR(120), request_mode) COLLATE Latin1_General_Bin2 AS request_mode,\r\n CONVERT(VARCHAR(120), request_status) COLLATE Latin1_General_Bin2 AS request_status,\r\n request_request_id\r\n FROM sys.dm_tran_locks\r\n ) AS tl\r\n ) AS x\r\n GROUP BY\r\n x.resource_type,\r\n x.database_name,\r\n x.object_id,\r\n x.file_id,\r\n CASE\r\n WHEN x.page_no = 1 OR x.page_no % 8088 = 0 THEN 'PFS'\r\n WHEN x.page_no = 2 OR x.page_no % 511232 = 0 THEN 'GAM'\r\n WHEN x.page_no = 3 OR (x.page_no - 1) % 511232 = 0 THEN 'SGAM'\r\n WHEN x.page_no = 6 OR (x.page_no - 6) % 511232 = 0 THEN 'DCM'\r\n WHEN x.page_no = 7 OR (x.page_no - 7) % 511232 = 0 THEN 'BCM'\r\n WHEN x.page_no IS NOT NULL THEN '*'\r\n ELSE NULL\r\n END,\r\n x.hobt_id,\r\n x.allocation_unit_id,\r\n x.index_id,\r\n x.schema_id,\r\n x.principal_id,\r\n x.request_mode,\r\n x.request_status,\r\n x.session_id,\r\n x.request_id,\r\n CASE\r\n WHEN COALESCE(x.object_id, x.file_id, x.hobt_id, x.allocation_unit_id, x.index_id, x.schema_id, x.principal_id) IS NULL THEN NULLIF(resource_description, '')\r\n ELSE NULL\r\n END\r\n ) AS y ON\r\n y.session_id = s.session_id\r\n AND y.request_id = s.request_id\r\n OPTION (HASH GROUP);\r\n\r\n --Disable unnecessary autostats on the table\r\n CREATE STATISTICS s_database_name ON #locks (database_name)\r\n WITH SAMPLE 0 ROWS, NORECOMPUTE;\r\n CREATE STATISTICS s_object_id ON #locks (object_id)\r\n WITH SAMPLE 0 ROWS, NORECOMPUTE;\r\n CREATE STATISTICS s_hobt_id ON #locks (hobt_id)\r\n WITH SAMPLE 0 ROWS, NORECOMPUTE;\r\n CREATE STATISTICS s_allocation_unit_id ON #locks (allocation_unit_id)\r\n WITH SAMPLE 0 ROWS, NORECOMPUTE;\r\n CREATE STATISTICS s_index_id ON #locks (index_id)\r\n WITH SAMPLE 0 ROWS, NORECOMPUTE;\r\n CREATE STATISTICS s_schema_id ON #locks (schema_id)\r\n WITH SAMPLE 0 ROWS, NORECOMPUTE;\r\n CREATE STATISTICS s_principal_id ON #locks (principal_id)\r\n WITH SAMPLE 0 ROWS, NORECOMPUTE;\r\n CREATE STATISTICS s_request_id ON #locks (request_id)\r\n WITH SAMPLE 0 ROWS, NORECOMPUTE;\r\n CREATE STATISTICS s_start_time ON #locks (start_time)\r\n WITH SAMPLE 0 ROWS, NORECOMPUTE;\r\n CREATE STATISTICS s_resource_type ON #locks (resource_type)\r\n WITH SAMPLE 0 ROWS, NORECOMPUTE;\r\n CREATE STATISTICS s_object_name ON #locks (object_name)\r\n WITH SAMPLE 0 ROWS, NORECOMPUTE;\r\n CREATE STATISTICS s_schema_name ON #locks (schema_name)\r\n WITH SAMPLE 0 ROWS, NORECOMPUTE;\r\n CREATE STATISTICS s_page_type ON #locks (page_type)\r\n WITH SAMPLE 0 ROWS, NORECOMPUTE;\r\n CREATE STATISTICS s_request_mode ON #locks (request_mode)\r\n WITH SAMPLE 0 ROWS, NORECOMPUTE;\r\n CREATE STATISTICS s_request_status ON #locks (request_status)\r\n WITH SAMPLE 0 ROWS, NORECOMPUTE;\r\n CREATE STATISTICS s_resource_description ON #locks (resource_description)\r\n WITH SAMPLE 0 ROWS, NORECOMPUTE;\r\n CREATE STATISTICS s_index_name ON #locks (index_name)\r\n WITH SAMPLE 0 ROWS, NORECOMPUTE;\r\n CREATE STATISTICS s_principal_name ON #locks (principal_name)\r\n WITH SAMPLE 0 ROWS, NORECOMPUTE;\r\n END;\r\n \r\n DECLARE\r\n @sql VARCHAR(MAX),\r\n @sql_n NVARCHAR(MAX),\r\n @core_session_join VARCHAR(MAX);\r\n\r\n SET @core_session_join =\r\n '@sessions AS sp\r\n LEFT OUTER LOOP JOIN sys.dm_exec_sessions AS s ON\r\n s.session_id = sp.session_id\r\n AND s.login_time = sp.login_time\r\n LEFT OUTER LOOP JOIN sys.dm_exec_requests AS r ON\r\n sp.status <> ''sleeping''\r\n AND r.session_id = sp.session_id\r\n AND r.request_id = sp.request_id\r\n AND\r\n (\r\n (\r\n s.is_user_process = 0\r\n AND sp.is_user_process = 0\r\n )\r\n OR\r\n (\r\n r.start_time = s.last_request_start_time\r\n AND s.last_request_end_time <= sp.last_request_end_time\r\n )\r\n ) ';\r\n\r\n SET @sql =\r\n CONVERT(VARCHAR(MAX), '') +\r\n 'DECLARE @blocker BIT;\r\n SET @blocker = 0;\r\n DECLARE @i INT;\r\n SET @i = 2147483647;\r\n\r\n DECLARE @sessions TABLE\r\n (\r\n session_id SMALLINT NOT NULL,\r\n request_id INT NOT NULL,\r\n login_time DATETIME,\r\n last_request_end_time DATETIME,\r\n status VARCHAR(30),\r\n statement_start_offset INT,\r\n statement_end_offset INT,\r\n sql_handle BINARY(20),\r\n host_name NVARCHAR(128),\r\n login_name NVARCHAR(128),\r\n program_name NVARCHAR(128),\r\n database_id SMALLINT,\r\n memory_usage INT,\r\n open_tran_count SMALLINT,\r\n ' +\r\n CASE\r\n WHEN\r\n (\r\n @get_task_info <> 0\r\n OR @find_block_leaders = 1\r\n ) THEN\r\n 'wait_type NVARCHAR(32),\r\n wait_resource NVARCHAR(256),\r\n wait_time BIGINT,\r\n '\r\n ELSE\r\n ''\r\n END +\r\n 'blocked SMALLINT,\r\n is_user_process BIT,\r\n cmd VARCHAR(32),\r\n PRIMARY KEY CLUSTERED (session_id, request_id) WITH (IGNORE_DUP_KEY = ON)\r\n );\r\n\r\n DECLARE @blockers TABLE\r\n (\r\n session_id INT NOT NULL PRIMARY KEY WITH (IGNORE_DUP_KEY = ON)\r\n );\r\n\r\n BLOCKERS:;\r\n\r\n INSERT @sessions\r\n (\r\n session_id,\r\n request_id,\r\n login_time,\r\n last_request_end_time,\r\n status,\r\n statement_start_offset,\r\n statement_end_offset,\r\n sql_handle,\r\n host_name,\r\n login_name,\r\n program_name,\r\n database_id,\r\n memory_usage,\r\n open_tran_count,\r\n ' +\r\n CASE\r\n WHEN\r\n (\r\n @get_task_info <> 0\r\n OR @find_block_leaders = 1\r\n ) THEN\r\n 'wait_type,\r\n wait_resource,\r\n wait_time,\r\n '\r\n ELSE\r\n ''\r\n END +\r\n 'blocked,\r\n is_user_process,\r\n cmd\r\n )\r\n SELECT TOP(@i)\r\n spy.session_id,\r\n spy.request_id,\r\n spy.login_time,\r\n spy.last_request_end_time,\r\n spy.status,\r\n spy.statement_start_offset,\r\n spy.statement_end_offset,\r\n spy.sql_handle,\r\n spy.host_name,\r\n spy.login_name,\r\n spy.program_name,\r\n spy.database_id,\r\n spy.memory_usage,\r\n spy.open_tran_count,\r\n ' +\r\n CASE\r\n WHEN\r\n (\r\n @get_task_info <> 0\r\n OR @find_block_leaders = 1\r\n ) THEN\r\n 'spy.wait_type,\r\n CASE\r\n WHEN\r\n spy.wait_type LIKE N''PAGE%LATCH_%''\r\n OR spy.wait_type IN (N''CXPACKET'', N''CXCONSUMER'', N''CXSYNC_PORT'', N''CXSYNC_CONSUMER'')\r\n OR spy.wait_type LIKE N''LATCH[_]%''\r\n OR spy.wait_type = N''OLEDB'' THEN\r\n spy.wait_resource\r\n ELSE\r\n NULL\r\n END AS wait_resource,\r\n spy.wait_time,\r\n '\r\n ELSE\r\n ''\r\n END +\r\n 'spy.blocked,\r\n spy.is_user_process,\r\n spy.cmd\r\n FROM\r\n (\r\n SELECT TOP(@i)\r\n spx.*,\r\n ' +\r\n CASE\r\n WHEN\r\n (\r\n @get_task_info <> 0\r\n OR @find_block_leaders = 1\r\n ) THEN\r\n 'ROW_NUMBER() OVER\r\n (\r\n PARTITION BY\r\n spx.session_id,\r\n spx.request_id\r\n ORDER BY\r\n CASE\r\n WHEN spx.wait_type LIKE N''LCK[_]%'' THEN\r\n 1\r\n ELSE\r\n 99\r\n END,\r\n spx.wait_time DESC,\r\n spx.blocked DESC\r\n ) AS r\r\n '\r\n ELSE\r\n '1 AS r\r\n '\r\n END +\r\n 'FROM\r\n (\r\n SELECT TOP(@i)\r\n sp0.session_id,\r\n sp0.request_id,\r\n sp0.login_time,\r\n sp0.last_request_end_time,\r\n LOWER(sp0.status) AS status,\r\n CASE\r\n WHEN sp0.cmd = ''CREATE INDEX'' THEN\r\n 0\r\n ELSE\r\n sp0.stmt_start\r\n END AS statement_start_offset,\r\n CASE\r\n WHEN sp0.cmd = N''CREATE INDEX'' THEN\r\n -1\r\n ELSE\r\n COALESCE(NULLIF(sp0.stmt_end, 0), -1)\r\n END AS statement_end_offset,\r\n sp0.sql_handle,\r\n sp0.host_name,\r\n sp0.login_name,\r\n sp0.program_name,\r\n sp0.database_id,\r\n sp0.memory_usage,\r\n sp0.open_tran_count,\r\n ' +\r\n CASE\r\n WHEN\r\n (\r\n @get_task_info <> 0\r\n OR @find_block_leaders = 1\r\n ) THEN\r\n 'CASE\r\n WHEN sp0.wait_time > 0 AND sp0.wait_type NOT IN (N''CXPACKET'', N''CXCONSUMER'', N''CXSYNC_PORT'', N''CXSYNC_CONSUMER'') THEN\r\n sp0.wait_type\r\n ELSE\r\n NULL\r\n END AS wait_type,\r\n CASE\r\n WHEN sp0.wait_time > 0 AND sp0.wait_type NOT IN (N''CXPACKET'', N''CXCONSUMER'', N''CXSYNC_PORT'', N''CXSYNC_CONSUMER'') THEN\r\n sp0.wait_resource\r\n ELSE\r\n NULL\r\n END AS wait_resource,\r\n CASE\r\n WHEN sp0.wait_type NOT IN (N''CXPACKET'', N''CXCONSUMER'', N''CXSYNC_PORT'', N''CXSYNC_CONSUMER'') THEN\r\n sp0.wait_time\r\n ELSE\r\n 0\r\n END AS wait_time,\r\n '\r\n ELSE\r\n ''\r\n END +\r\n 'sp0.blocked,\r\n sp0.is_user_process,\r\n sp0.cmd\r\n FROM\r\n (\r\n SELECT TOP(@i)\r\n sp1.session_id,\r\n sp1.request_id,\r\n sp1.login_time,\r\n sp1.last_request_end_time,\r\n sp1.status,\r\n sp1.cmd,\r\n sp1.stmt_start,\r\n sp1.stmt_end,\r\n MAX(NULLIF(sp1.sql_handle, 0x00)) OVER (PARTITION BY sp1.session_id, sp1.request_id) AS sql_handle,\r\n sp1.host_name,\r\n MAX(sp1.login_name) OVER (PARTITION BY sp1.session_id, sp1.request_id) AS login_name,\r\n sp1.program_name,\r\n sp1.database_id,\r\n MAX(sp1.memory_usage) OVER (PARTITION BY sp1.session_id, sp1.request_id) AS memory_usage,\r\n MAX(sp1.open_tran_count) OVER (PARTITION BY sp1.session_id, sp1.request_id) AS open_tran_count,\r\n sp1.wait_type,\r\n sp1.wait_resource,\r\n sp1.wait_time,\r\n sp1.blocked,\r\n sp1.hostprocess,\r\n sp1.is_user_process\r\n FROM\r\n (\r\n SELECT TOP(@i)\r\n sp2.spid AS session_id,\r\n v2.request_id,\r\n MAX(sp2.login_time) AS login_time,\r\n MAX(sp2.last_batch) AS last_request_end_time,\r\n MAX(CONVERT(VARCHAR(30), RTRIM(sp2.status)) COLLATE Latin1_General_Bin2) AS status,\r\n MAX(CONVERT(VARCHAR(32), RTRIM(sp2.cmd)) COLLATE Latin1_General_Bin2) AS cmd,\r\n MAX(sp2.stmt_start) AS stmt_start,\r\n MAX(sp2.stmt_end) AS stmt_end,\r\n MAX(sp2.sql_handle) AS sql_handle,\r\n MAX(CONVERT(sysname, RTRIM(sp2.hostname)) COLLATE SQL_Latin1_General_CP1_CI_AS) AS host_name,\r\n MAX(CONVERT(sysname, RTRIM(sp2.loginame)) COLLATE SQL_Latin1_General_CP1_CI_AS) AS login_name,\r\n MAX\r\n (\r\n CASE\r\n WHEN blk.queue_id IS NOT NULL THEN\r\n N''Service Broker\r\n database_id: '' + CONVERT(NVARCHAR, blk.database_id) +\r\n N'' queue_id: '' + CONVERT(NVARCHAR, blk.queue_id)\r\n ELSE\r\n CONVERT\r\n (\r\n sysname,\r\n RTRIM(sp2.program_name)\r\n )\r\n END COLLATE SQL_Latin1_General_CP1_CI_AS\r\n ) AS program_name,\r\n MAX(sp2.dbid) AS database_id,\r\n MAX(sp2.memusage) AS memory_usage,\r\n MAX(sp2.open_tran) AS open_tran_count,\r\n RTRIM(sp2.lastwaittype) AS wait_type,\r\n v2.wait_resource,\r\n MAX(sp2.waittime) AS wait_time,\r\n COALESCE(NULLIF(sp2.blocked, sp2.spid), 0) AS blocked,\r\n MAX\r\n (\r\n CASE\r\n WHEN blk.session_id = sp2.spid THEN\r\n ''blocker''\r\n ELSE\r\n RTRIM(sp2.hostprocess)\r\n END\r\n ) AS hostprocess,\r\n CONVERT\r\n (\r\n BIT,\r\n MAX\r\n (\r\n CASE\r\n WHEN sp2.hostprocess > '''' THEN\r\n 1\r\n ELSE\r\n 0\r\n END\r\n )\r\n ) AS is_user_process\r\n FROM\r\n (\r\n SELECT TOP(@i)\r\n session_id,\r\n CONVERT(INT, NULL) AS queue_id,\r\n CONVERT(INT, NULL) AS database_id\r\n FROM @blockers\r\n\r\n UNION ALL\r\n\r\n SELECT TOP(@i)\r\n CONVERT(SMALLINT, 0),\r\n CONVERT(INT, NULL) AS queue_id,\r\n CONVERT(INT, NULL) AS database_id\r\n WHERE\r\n @blocker = 0\r\n\r\n UNION ALL\r\n\r\n SELECT TOP(@i)\r\n CONVERT(SMALLINT, spid),\r\n queue_id,\r\n database_id\r\n FROM sys.dm_broker_activated_tasks\r\n WHERE\r\n @blocker = 0\r\n ) AS blk\r\n INNER JOIN sys.sysprocesses AS sp2 ON\r\n sp2.spid = blk.session_id\r\n OR\r\n (\r\n blk.session_id = 0\r\n AND @blocker = 0\r\n )\r\n CROSS APPLY\r\n (\r\n SELECT\r\n CASE sp2.status\r\n WHEN ''sleeping'' THEN\r\n CONVERT(INT, 0)\r\n ELSE\r\n sp2.request_id\r\n END AS request_id,\r\n RTRIM\r\n (\r\n LEFT\r\n (\r\n sp2.waitresource COLLATE Latin1_General_Bin2,\r\n ISNULL(NULLIF(CHARINDEX('' (LATCH '', sp2.waitresource COLLATE Latin1_General_Bin2) - 1, -1), 256)\r\n )\r\n ) AS wait_resource\r\n ) AS v2\r\n ' +\r\n CASE\r\n WHEN\r\n (\r\n @get_task_info = 0\r\n AND @find_block_leaders = 0\r\n ) THEN\r\n 'WHERE\r\n sp2.ecid = 0\r\n '\r\n ELSE\r\n ''\r\n END +\r\n 'GROUP BY\r\n sp2.spid,\r\n v2.request_id,\r\n RTRIM(sp2.lastwaittype),\r\n v2.wait_resource,\r\n COALESCE(NULLIF(sp2.blocked, sp2.spid), 0)\r\n ) AS sp1\r\n ) AS sp0\r\n WHERE\r\n @blocker = 1\r\n OR\r\n (1=1\r\n ' +\r\n --inclusive filter\r\n CASE\r\n WHEN @filter <> '' THEN\r\n CASE @filter_type\r\n WHEN 'session' THEN\r\n CASE\r\n WHEN CONVERT(SMALLINT, @filter) <> 0 THEN\r\n 'AND sp0.session_id = CONVERT(SMALLINT, @filter)\r\n '\r\n ELSE\r\n ''\r\n END\r\n WHEN 'program' THEN\r\n 'AND sp0.program_name LIKE @filter\r\n '\r\n WHEN 'login' THEN\r\n 'AND sp0.login_name LIKE @filter\r\n '\r\n WHEN 'host' THEN\r\n 'AND sp0.host_name LIKE @filter\r\n '\r\n WHEN 'database' THEN\r\n 'AND DB_NAME(sp0.database_id) LIKE @filter\r\n '\r\n ELSE\r\n ''\r\n END\r\n ELSE\r\n ''\r\n END +\r\n --exclusive filter\r\n CASE\r\n WHEN @not_filter <> '' THEN\r\n CASE @not_filter_type\r\n WHEN 'session' THEN\r\n CASE\r\n WHEN CONVERT(SMALLINT, @not_filter) <> 0 THEN\r\n 'AND sp0.session_id <> CONVERT(SMALLINT, @not_filter)\r\n '\r\n ELSE\r\n ''\r\n END\r\n WHEN 'program' THEN\r\n 'AND sp0.program_name NOT LIKE @not_filter\r\n '\r\n WHEN 'login' THEN\r\n 'AND sp0.login_name NOT LIKE @not_filter\r\n '\r\n WHEN 'host' THEN\r\n 'AND sp0.host_name NOT LIKE @not_filter\r\n '\r\n WHEN 'database' THEN\r\n 'AND DB_NAME(sp0.database_id) NOT LIKE @not_filter\r\n '\r\n ELSE\r\n ''\r\n END\r\n ELSE\r\n ''\r\n END +\r\n CASE @show_own_spid\r\n WHEN 1 THEN\r\n ''\r\n ELSE\r\n 'AND sp0.session_id <> @@spid\r\n '\r\n END +\r\n CASE\r\n WHEN @show_system_spids = 0 THEN\r\n 'AND sp0.hostprocess > ''''\r\n '\r\n ELSE\r\n ''\r\n END +\r\n CASE @show_sleeping_spids\r\n WHEN 0 THEN\r\n 'AND sp0.status <> ''sleeping''\r\n '\r\n WHEN 1 THEN\r\n 'AND\r\n (\r\n sp0.status <> ''sleeping''\r\n OR sp0.open_tran_count > 0\r\n )\r\n '\r\n ELSE\r\n ''\r\n END +\r\n ')\r\n ) AS spx\r\n ) AS spy\r\n WHERE\r\n spy.r = 1;\r\n ' +\r\n CASE @recursion\r\n WHEN 1 THEN\r\n 'IF @@ROWCOUNT > 0\r\n BEGIN;\r\n INSERT @blockers\r\n (\r\n session_id\r\n )\r\n SELECT TOP(@i)\r\n blocked\r\n FROM @sessions\r\n WHERE\r\n NULLIF(blocked, 0) IS NOT NULL\r\n\r\n EXCEPT\r\n\r\n SELECT TOP(@i)\r\n session_id\r\n FROM @sessions;\r\n ' +\r\n\r\n CASE\r\n WHEN\r\n (\r\n @get_task_info > 0\r\n OR @find_block_leaders = 1\r\n ) THEN\r\n 'IF @@ROWCOUNT > 0\r\n BEGIN;\r\n SET @blocker = 1;\r\n GOTO BLOCKERS;\r\n END;\r\n '\r\n ELSE\r\n ''\r\n END +\r\n 'END;\r\n '\r\n ELSE\r\n ''\r\n END +\r\n 'SELECT TOP(@i)\r\n @recursion AS recursion,\r\n x.session_id,\r\n x.request_id,\r\n DENSE_RANK() OVER\r\n (\r\n ORDER BY\r\n x.session_id\r\n ) AS session_number,\r\n ' +\r\n CASE\r\n WHEN @output_column_list LIKE '%|[dd hh:mm:ss.mss|]%' ESCAPE '|' THEN\r\n 'x.elapsed_time '\r\n ELSE\r\n '0 '\r\n END +\r\n 'AS elapsed_time,\r\n ' +\r\n CASE\r\n WHEN\r\n (\r\n @output_column_list LIKE '%|[dd hh:mm:ss.mss (avg)|]%' ESCAPE '|' OR\r\n @output_column_list LIKE '%|[avg_elapsed_time|]%' ESCAPE '|'\r\n )\r\n AND @recursion = 1\r\n THEN\r\n 'x.avg_elapsed_time / 1000 '\r\n ELSE\r\n 'NULL '\r\n END +\r\n 'AS avg_elapsed_time,\r\n ' +\r\n CASE\r\n WHEN\r\n @output_column_list LIKE '%|[physical_io|]%' ESCAPE '|'\r\n OR @output_column_list LIKE '%|[physical_io_delta|]%' ESCAPE '|'\r\n THEN\r\n 'x.physical_io '\r\n ELSE\r\n 'NULL '\r\n END +\r\n 'AS physical_io,\r\n ' +\r\n CASE\r\n WHEN\r\n @output_column_list LIKE '%|[reads|]%' ESCAPE '|'\r\n OR @output_column_list LIKE '%|[reads_delta|]%' ESCAPE '|'\r\n THEN\r\n 'x.reads '\r\n ELSE\r\n '0 '\r\n END +\r\n 'AS reads,\r\n ' +\r\n CASE\r\n WHEN\r\n @output_column_list LIKE '%|[physical_reads|]%' ESCAPE '|'\r\n OR @output_column_list LIKE '%|[physical_reads_delta|]%' ESCAPE '|'\r\n THEN\r\n 'x.physical_reads '\r\n ELSE\r\n '0 '\r\n END +\r\n 'AS physical_reads,\r\n ' +\r\n CASE\r\n WHEN\r\n @output_column_list LIKE '%|[writes|]%' ESCAPE '|'\r\n OR @output_column_list LIKE '%|[writes_delta|]%' ESCAPE '|'\r\n THEN\r\n 'x.writes '\r\n ELSE\r\n '0 '\r\n END +\r\n 'AS writes,\r\n ' +\r\n CASE\r\n WHEN\r\n @output_column_list LIKE '%|[tempdb_allocations|]%' ESCAPE '|'\r\n OR @output_column_list LIKE '%|[tempdb_allocations_delta|]%' ESCAPE '|'\r\n THEN\r\n 'x.tempdb_allocations '\r\n ELSE\r\n '0 '\r\n END +\r\n 'AS tempdb_allocations,\r\n ' +\r\n CASE\r\n WHEN\r\n @output_column_list LIKE '%|[tempdb_current|]%' ESCAPE '|'\r\n OR @output_column_list LIKE '%|[tempdb_current_delta|]%' ESCAPE '|'\r\n THEN\r\n 'x.tempdb_current '\r\n ELSE\r\n '0 '\r\n END +\r\n 'AS tempdb_current,\r\n ' +\r\n CASE\r\n WHEN\r\n @output_column_list LIKE '%|[CPU|]%' ESCAPE '|'\r\n OR @output_column_list LIKE '%|[CPU_delta|]%' ESCAPE '|'\r\n THEN\r\n 'x.CPU '\r\n ELSE\r\n '0 '\r\n END +\r\n 'AS CPU,\r\n ' +\r\n CASE\r\n WHEN\r\n @output_column_list LIKE '%|[CPU_delta|]%' ESCAPE '|'\r\n AND @get_task_info = 2\r\n AND @sys_info = 1\r\n THEN\r\n 'x.thread_CPU_snapshot '\r\n ELSE\r\n '0 '\r\n END +\r\n 'AS thread_CPU_snapshot,\r\n ' +\r\n CASE\r\n WHEN\r\n @output_column_list LIKE '%|[context_switches|]%' ESCAPE '|'\r\n OR @output_column_list LIKE '%|[context_switches_delta|]%' ESCAPE '|'\r\n THEN\r\n 'x.context_switches '\r\n ELSE\r\n 'NULL '\r\n END +\r\n 'AS context_switches,\r\n ' +\r\n CASE\r\n WHEN\r\n @output_column_list LIKE '%|[used_memory|]%' ESCAPE '|'\r\n OR @output_column_list LIKE '%|[used_memory_delta|]%' ESCAPE '|'\r\n THEN\r\n CASE\r\n WHEN @get_memory_info = 1 THEN\r\n 'COALESCE(x.mg_used_memory_kb / 8, x.used_memory) '\r\n ELSE\r\n 'x.used_memory '\r\n END\r\n ELSE\r\n '0 '\r\n END +\r\n 'AS used_memory,\r\n ' +\r\n CASE\r\n WHEN\r\n @output_column_list LIKE '%|[max_used_memory|]%' ESCAPE '|'\r\n OR @output_column_list LIKE '%|[max_used_memory_delta|]%' ESCAPE '|'\r\n THEN\r\n 'x.max_used_memory_kb / 8 '\r\n ELSE\r\n '0 '\r\n END +\r\n 'AS max_used_memory,\r\n ' +\r\n CASE\r\n WHEN\r\n @output_column_list LIKE '%|[requested_memory|]%' ESCAPE '|'\r\n THEN\r\n 'x.requested_memory_kb / 8 '\r\n ELSE\r\n '0 '\r\n END +\r\n 'AS requested_memory,\r\n ' +\r\n CASE\r\n WHEN\r\n @output_column_list LIKE '%|[granted_memory|]%' ESCAPE '|'\r\n THEN\r\n 'x.mg_granted_memory_kb / 8 '\r\n ELSE\r\n '0 '\r\n END +\r\n 'AS granted_memory,\r\n ' +\r\n CASE\r\n WHEN\r\n @output_column_list LIKE '%|[tasks|]%' ESCAPE '|'\r\n AND @recursion = 1\r\n THEN\r\n 'x.tasks '\r\n ELSE\r\n 'NULL '\r\n END +\r\n 'AS tasks,\r\n ' +\r\n CASE\r\n WHEN\r\n (\r\n @output_column_list LIKE '%|[status|]%' ESCAPE '|'\r\n OR @output_column_list LIKE '%|[sql_command|]%' ESCAPE '|'\r\n )\r\n AND @recursion = 1\r\n THEN\r\n 'x.status '\r\n ELSE\r\n ''''' '\r\n END +\r\n 'AS status,\r\n ' +\r\n CASE\r\n WHEN\r\n @output_column_list LIKE '%|[wait_info|]%' ESCAPE '|'\r\n AND @recursion = 1\r\n THEN\r\n CASE @get_task_info\r\n WHEN 2 THEN\r\n 'COALESCE(x.task_wait_info, x.sys_wait_info) '\r\n ELSE\r\n 'x.sys_wait_info '\r\n END\r\n ELSE\r\n 'NULL '\r\n END +\r\n 'AS wait_info,\r\n ' +\r\n CASE\r\n WHEN\r\n (\r\n @output_column_list LIKE '%|[tran_start_time|]%' ESCAPE '|'\r\n OR @output_column_list LIKE '%|[tran_log_writes|]%' ESCAPE '|'\r\n )\r\n AND @recursion = 1\r\n THEN\r\n 'x.transaction_id '\r\n ELSE\r\n 'NULL '\r\n END +\r\n 'AS transaction_id,\r\n ' +\r\n CASE\r\n WHEN\r\n @output_column_list LIKE '%|[open_tran_count|]%' ESCAPE '|'\r\n AND @recursion = 1\r\n THEN\r\n 'x.open_tran_count '\r\n ELSE\r\n 'NULL '\r\n END +\r\n 'AS open_tran_count,\r\n ' +\r\n CASE\r\n WHEN\r\n @output_column_list LIKE '%|[sql_text|]%' ESCAPE '|'\r\n AND @recursion = 1\r\n THEN\r\n 'x.sql_handle '\r\n ELSE\r\n 'NULL '\r\n END +\r\n 'AS sql_handle,\r\n ' +\r\n CASE\r\n WHEN\r\n (\r\n @output_column_list LIKE '%|[sql_text|]%' ESCAPE '|'\r\n OR @output_column_list LIKE '%|[query_plan|]%' ESCAPE '|'\r\n )\r\n AND @recursion = 1\r\n THEN\r\n 'x.statement_start_offset '\r\n ELSE\r\n 'NULL '\r\n END +\r\n 'AS statement_start_offset,\r\n ' +\r\n CASE\r\n WHEN\r\n (\r\n @output_column_list LIKE '%|[sql_text|]%' ESCAPE '|'\r\n OR @output_column_list LIKE '%|[query_plan|]%' ESCAPE '|'\r\n )\r\n AND @recursion = 1\r\n THEN\r\n 'x.statement_end_offset '\r\n ELSE\r\n 'NULL '\r\n END +\r\n 'AS statement_end_offset,\r\n ' +\r\n 'NULL AS sql_text,\r\n ' +\r\n CASE\r\n WHEN\r\n @output_column_list LIKE '%|[query_plan|]%' ESCAPE '|'\r\n AND @recursion = 1\r\n THEN\r\n 'x.plan_handle '\r\n ELSE\r\n 'NULL '\r\n END +\r\n 'AS plan_handle,\r\n ' +\r\n CASE\r\n WHEN\r\n @output_column_list LIKE '%|[blocking_session_id|]%' ESCAPE '|' OR @find_block_leaders = 1\r\n AND @recursion = 1\r\n THEN\r\n 'NULLIF(x.blocking_session_id, 0) '\r\n ELSE\r\n 'NULL '\r\n END +\r\n 'AS blocking_session_id,\r\n ' +\r\n CASE\r\n WHEN\r\n @output_column_list LIKE '%|[percent_complete|]%' ESCAPE '|'\r\n AND @recursion = 1\r\n THEN\r\n 'x.percent_complete '\r\n ELSE\r\n 'NULL '\r\n END +\r\n 'AS percent_complete,\r\n ' +\r\n CASE\r\n WHEN\r\n @output_column_list LIKE '%|[host_name|]%' ESCAPE '|'\r\n AND @recursion = 1\r\n THEN\r\n 'x.host_name '\r\n ELSE\r\n ''''' '\r\n END +\r\n 'AS host_name,\r\n ' +\r\n CASE\r\n WHEN\r\n @output_column_list LIKE '%|[login_name|]%' ESCAPE '|'\r\n AND @recursion = 1\r\n THEN\r\n 'x.login_name '\r\n ELSE\r\n ''''' '\r\n END +\r\n 'AS login_name,\r\n ' +\r\n CASE\r\n WHEN\r\n @output_column_list LIKE '%|[database_name|]%' ESCAPE '|'\r\n AND @recursion = 1\r\n THEN\r\n 'DB_NAME(x.database_id) '\r\n ELSE\r\n 'NULL '\r\n END +\r\n 'AS database_name,\r\n ' +\r\n CASE\r\n WHEN\r\n @output_column_list LIKE '%|[program_name|]%' ESCAPE '|'\r\n AND @recursion = 1\r\n THEN\r\n 'x.program_name '\r\n ELSE\r\n ''''' '\r\n END +\r\n 'AS program_name,\r\n ' +\r\n CASE\r\n WHEN\r\n @output_column_list LIKE '%|[additional_info|]%' ESCAPE '|'\r\n AND @recursion = 1\r\n THEN\r\n '(\r\n SELECT TOP(@i)\r\n x.text_size,\r\n x.language,\r\n x.date_format,\r\n x.date_first,\r\n CASE x.quoted_identifier\r\n WHEN 0 THEN ''OFF''\r\n WHEN 1 THEN ''ON''\r\n END AS quoted_identifier,\r\n CASE x.arithabort\r\n WHEN 0 THEN ''OFF''\r\n WHEN 1 THEN ''ON''\r\n END AS arithabort,\r\n CASE x.ansi_null_dflt_on\r\n WHEN 0 THEN ''OFF''\r\n WHEN 1 THEN ''ON''\r\n END AS ansi_null_dflt_on,\r\n CASE x.ansi_defaults\r\n WHEN 0 THEN ''OFF''\r\n WHEN 1 THEN ''ON''\r\n END AS ansi_defaults,\r\n CASE x.ansi_warnings\r\n WHEN 0 THEN ''OFF''\r\n WHEN 1 THEN ''ON''\r\n END AS ansi_warnings,\r\n CASE x.ansi_padding\r\n WHEN 0 THEN ''OFF''\r\n WHEN 1 THEN ''ON''\r\n END AS ansi_padding,\r\n CASE ansi_nulls\r\n WHEN 0 THEN ''OFF''\r\n WHEN 1 THEN ''ON''\r\n END AS ansi_nulls,\r\n CASE x.concat_null_yields_null\r\n WHEN 0 THEN ''OFF''\r\n WHEN 1 THEN ''ON''\r\n END AS concat_null_yields_null,\r\n CASE x.transaction_isolation_level\r\n WHEN 0 THEN ''Unspecified''\r\n WHEN 1 THEN ''ReadUncomitted''\r\n WHEN 2 THEN ''ReadCommitted''\r\n WHEN 3 THEN ''Repeatable''\r\n WHEN 4 THEN ''Serializable''\r\n WHEN 5 THEN ''Snapshot''\r\n END AS transaction_isolation_level,\r\n x.lock_timeout,\r\n x.deadlock_priority,\r\n x.row_count,\r\n x.command_type,\r\n ' +\r\n CASE\r\n WHEN OBJECT_ID('master.dbo.fn_varbintohexstr') IS NOT NULL THEN\r\n 'master.dbo.fn_varbintohexstr(x.sql_handle) AS sql_handle,\r\n master.dbo.fn_varbintohexstr(x.plan_handle) AS plan_handle,'\r\n ELSE\r\n 'CONVERT(VARCHAR(256), x.sql_handle, 1) AS sql_handle,\r\n CONVERT(VARCHAR(256), x.plan_handle, 1) AS plan_handle,'\r\n END +\r\n '\r\n x.statement_start_offset,\r\n x.statement_end_offset,\r\n ' +\r\n CASE\r\n WHEN @output_column_list LIKE '%|[program_name|]%' ESCAPE '|' THEN\r\n '(\r\n SELECT TOP(1)\r\n CONVERT(uniqueidentifier, CONVERT(XML, '''').value(''xs:hexBinary( substring(sql:column(\"agent_info.job_id_string\"), 0) )'', ''binary(16)'')) AS job_id,\r\n agent_info.step_id,\r\n (\r\n SELECT TOP(1)\r\n NULL\r\n FOR XML\r\n PATH(''job_name''),\r\n TYPE\r\n ),\r\n (\r\n SELECT TOP(1)\r\n NULL\r\n FOR XML\r\n PATH(''step_name''),\r\n TYPE\r\n )\r\n FROM\r\n (\r\n SELECT TOP(1)\r\n SUBSTRING(x.program_name, CHARINDEX(''0x'', x.program_name) + 2, 32) AS job_id_string,\r\n SUBSTRING(x.program_name, CHARINDEX('': Step '', x.program_name) + 7, CHARINDEX('')'', x.program_name, CHARINDEX('': Step '', x.program_name)) - (CHARINDEX('': Step '', x.program_name) + 7)) AS step_id\r\n WHERE\r\n x.program_name LIKE N''SQLAgent - TSQL JobStep (Job 0x%''\r\n ) AS agent_info\r\n FOR XML\r\n PATH(''agent_job_info''),\r\n TYPE\r\n ),\r\n '\r\n ELSE ''\r\n END +\r\n CASE\r\n WHEN @get_task_info = 2 THEN\r\n 'CONVERT(XML, x.block_info) AS block_info,\r\n '\r\n ELSE\r\n ''\r\n END + '\r\n x.host_process_id,\r\n x.group_id,\r\n x.original_login_name,\r\n ' +\r\n CASE\r\n WHEN OBJECT_ID('master.dbo.fn_varbintohexstr') IS NOT NULL THEN\r\n 'master.dbo.fn_varbintohexstr(x.context_info) AS context_info'\r\n ELSE\r\n 'CONVERT(VARCHAR(256), x.context_info, 1) AS context_info'\r\n END + '\r\n FOR XML\r\n PATH(''additional_info''),\r\n TYPE\r\n ) '\r\n ELSE\r\n 'NULL '\r\n END +\r\n 'AS additional_info,\r\n ' +\r\n CASE\r\n WHEN\r\n @output_column_list LIKE '%|[memory_info|]%' ESCAPE '|'\r\n AND @get_memory_info = 1 THEN'\r\n (\r\n SELECT TOP(@i)\r\n (\r\n SELECT TOP(@i) \r\n x.request_time,\r\n x.grant_time,\r\n x.wait_time_ms,\r\n x.requested_memory_kb, \r\n x.mg_granted_memory_kb AS granted_memory_kb,\r\n x.mg_used_memory_kb AS used_memory_kb,\r\n x.max_used_memory_kb,\r\n x.ideal_memory_kb, \r\n x.required_memory_kb,\r\n x.queue_id,\r\n x.wait_order,\r\n x.is_next_candidate,\r\n x.dop,\r\n CAST(x.query_cost AS NUMERIC(38, 4)) AS query_cost\r\n FOR XML\r\n PATH(''memory_grant''),\r\n TYPE\r\n ),\r\n (\r\n SELECT TOP(@i)\r\n x.timeout_error_count,\r\n x.target_memory_kb,\r\n x.max_target_memory_kb,\r\n x.total_memory_kb,\r\n x.available_memory_kb,\r\n x.rs_granted_memory_kb AS granted_memory_kb,\r\n x.rs_used_memory_kb AS used_memory_kb,\r\n x.grantee_count,\r\n x.waiter_count\r\n FOR XML\r\n PATH(''resource_semaphore''),\r\n TYPE\r\n ),\r\n (\r\n SELECT TOP(@i) \r\n x.wg_name AS name,\r\n x.request_max_memory_grant_percent,\r\n x.request_max_cpu_time_sec,\r\n x.request_memory_grant_timeout_sec,\r\n x.max_dop\r\n FOR XML\r\n PATH(''workload_group''),\r\n TYPE\r\n ),\r\n (\r\n SELECT TOP(@i) \r\n x.rp_name AS name,\r\n x.min_memory_percent,\r\n x.max_memory_percent,\r\n x.min_cpu_percent,\r\n x.max_cpu_percent\r\n FOR XML\r\n PATH(''resource_pool''),\r\n TYPE\r\n )\r\n WHERE\r\n x.request_time IS NOT NULL\r\n FOR XML\r\n PATH(''memory_info''),\r\n TYPE\r\n ) \r\n '\r\n ELSE\r\n 'NULL '\r\n END + 'AS memory_info,\r\n x.start_time,\r\n '\r\n +\r\n CASE\r\n WHEN\r\n @output_column_list LIKE '%|[login_time|]%' ESCAPE '|'\r\n AND @recursion = 1\r\n THEN\r\n 'x.login_time '\r\n ELSE\r\n 'NULL '\r\n END +\r\n 'AS login_time,\r\n x.last_request_start_time\r\n FROM\r\n (\r\n SELECT TOP(@i)\r\n y.*,\r\n CASE\r\n WHEN DATEDIFF(hour, y.start_time, GETDATE()) > 576 THEN\r\n DATEDIFF(second, GETDATE(), y.start_time)\r\n ELSE DATEDIFF(ms, y.start_time, GETDATE())\r\n END AS elapsed_time,\r\n COALESCE(tempdb_info.tempdb_allocations, 0) AS tempdb_allocations,\r\n COALESCE\r\n (\r\n CASE\r\n WHEN tempdb_info.tempdb_current < 0 THEN 0\r\n ELSE tempdb_info.tempdb_current\r\n END,\r\n 0\r\n ) AS tempdb_current,\r\n ' +\r\n CASE\r\n WHEN\r\n (\r\n @get_task_info <> 0\r\n OR @find_block_leaders = 1\r\n ) THEN\r\n 'N''('' + CONVERT(NVARCHAR, y.wait_duration_ms) + N''ms)'' +\r\n y.wait_type +\r\n CASE\r\n WHEN y.wait_type LIKE N''PAGE%LATCH_%'' THEN\r\n N'':'' +\r\n COALESCE(DB_NAME(CONVERT(INT, LEFT(y.resource_description, CHARINDEX(N'':'', y.resource_description) - 1))), N''(null)'') +\r\n N'':'' +\r\n SUBSTRING(y.resource_description, CHARINDEX(N'':'', y.resource_description) + 1, LEN(y.resource_description) - CHARINDEX(N'':'', REVERSE(y.resource_description)) - CHARINDEX(N'':'', y.resource_description)) +\r\n N''('' +\r\n CASE\r\n WHEN\r\n CONVERT(INT, RIGHT(y.resource_description, CHARINDEX(N'':'', REVERSE(y.resource_description)) - 1)) = 1 OR\r\n CONVERT(INT, RIGHT(y.resource_description, CHARINDEX(N'':'', REVERSE(y.resource_description)) - 1)) % 8088 = 0\r\n THEN\r\n N''PFS''\r\n WHEN\r\n CONVERT(INT, RIGHT(y.resource_description, CHARINDEX(N'':'', REVERSE(y.resource_description)) - 1)) = 2 OR\r\n CONVERT(INT, RIGHT(y.resource_description, CHARINDEX(N'':'', REVERSE(y.resource_description)) - 1)) % 511232 = 0\r\n THEN\r\n N''GAM''\r\n WHEN\r\n CONVERT(INT, RIGHT(y.resource_description, CHARINDEX(N'':'', REVERSE(y.resource_description)) - 1)) = 3 OR\r\n (CONVERT(INT, RIGHT(y.resource_description, CHARINDEX(N'':'', REVERSE(y.resource_description)) - 1)) - 1) % 511232 = 0\r\n THEN\r\n N''SGAM''\r\n WHEN\r\n CONVERT(INT, RIGHT(y.resource_description, CHARINDEX(N'':'', REVERSE(y.resource_description)) - 1)) = 6 OR\r\n (CONVERT(INT, RIGHT(y.resource_description, CHARINDEX(N'':'', REVERSE(y.resource_description)) - 1)) - 6) % 511232 = 0\r\n THEN\r\n N''DCM''\r\n WHEN\r\n CONVERT(INT, RIGHT(y.resource_description, CHARINDEX(N'':'', REVERSE(y.resource_description)) - 1)) = 7 OR\r\n (CONVERT(INT, RIGHT(y.resource_description, CHARINDEX(N'':'', REVERSE(y.resource_description)) - 1)) - 7) % 511232 = 0\r\n THEN\r\n N''BCM''\r\n ELSE\r\n N''*''\r\n END +\r\n N'')''\r\n WHEN y.wait_type IN (N''CXPACKET'', N''CXCONSUMER'', N''CXSYNC_PORT'', N''CXSYNC_CONSUMER'') THEN\r\n N'':'' +\r\n SUBSTRING\r\n (\r\n y.resource_description,\r\n CHARINDEX(N''nodeId'', y.resource_description) + 7,\r\n CASE\r\n WHEN CHARINDEX(N'' '', y.resource_description, CHARINDEX(N''nodeId'', y.resource_description)) > 0\r\n THEN CHARINDEX(N'' '', y.resource_description, CHARINDEX(N''nodeId'', y.resource_description) + 7) - 7 - CHARINDEX(N''nodeId'', y.resource_description)\r\n ELSE 4\r\n END\r\n )\r\n WHEN y.wait_type LIKE N''LATCH[_]%'' THEN\r\n N'' ['' + LEFT(y.resource_description, COALESCE(NULLIF(CHARINDEX(N'' '', y.resource_description), 0), LEN(y.resource_description) + 1) - 1) + N'']''\r\n WHEN\r\n y.wait_type = N''OLEDB''\r\n AND y.resource_description LIKE N''%(SPID=%)'' THEN\r\n N''['' + LEFT(y.resource_description, CHARINDEX(N''(SPID='', y.resource_description) - 2) +\r\n N'':'' + SUBSTRING(y.resource_description, CHARINDEX(N''(SPID='', y.resource_description) + 6, CHARINDEX(N'')'', y.resource_description, (CHARINDEX(N''(SPID='', y.resource_description) + 6)) - (CHARINDEX(N''(SPID='', y.resource_description) + 6)) + '']''\r\n ELSE\r\n N''''\r\n END COLLATE Latin1_General_Bin2 AS sys_wait_info,\r\n '\r\n ELSE\r\n ''\r\n END +\r\n CASE\r\n WHEN @get_task_info = 2 THEN\r\n 'tasks.physical_io,\r\n tasks.context_switches,\r\n tasks.tasks,\r\n tasks.block_info,\r\n tasks.wait_info AS task_wait_info,\r\n tasks.thread_CPU_snapshot,\r\n '\r\n ELSE\r\n ''\r\n END +\r\n CASE\r\n WHEN NOT (@get_avg_time = 1 AND @recursion = 1) THEN\r\n 'CONVERT(INT, NULL) '\r\n ELSE\r\n 'qs.total_elapsed_time / qs.execution_count '\r\n END +\r\n 'AS avg_elapsed_time\r\n FROM\r\n (\r\n SELECT TOP(@i)\r\n sp.session_id,\r\n sp.request_id,\r\n COALESCE(r.logical_reads, s.logical_reads) AS reads,\r\n COALESCE(r.reads, s.reads) AS physical_reads,\r\n COALESCE(r.writes, s.writes) AS writes,\r\n COALESCE(r.CPU_time, s.CPU_time) AS CPU,\r\n ' +\r\n CASE\r\n WHEN @get_memory_info = 1 THEN\r\n 'sp.memory_usage AS used_memory,\r\n mg.used_memory_kb AS mg_used_memory_kb,\r\n mg.max_used_memory_kb,\r\n mg.request_time,\r\n mg.grant_time,\r\n mg.wait_time_ms,\r\n mg.requested_memory_kb,\r\n mg.granted_memory_kb AS mg_granted_memory_kb,\r\n mg.required_memory_kb,\r\n mg.ideal_memory_kb,\r\n mg.dop AS dop,\r\n mg.query_cost AS query_cost,\r\n mg.queue_id AS queue_id,\r\n mg.wait_order AS wait_order,\r\n mg.is_next_candidate,\r\n rs.target_memory_kb,\r\n rs.max_target_memory_kb,\r\n rs.total_memory_kb,\r\n rs.available_memory_kb,\r\n rs.granted_memory_kb AS rs_granted_memory_kb,\r\n rs.used_memory_kb AS rs_used_memory_kb,\r\n rs.grantee_count,\r\n rs.waiter_count,\r\n rs.timeout_error_count,\r\n wg.name AS wg_name,\r\n wg.request_max_memory_grant_percent,\r\n wg.request_max_cpu_time_sec,\r\n wg.request_memory_grant_timeout_sec,\r\n wg.max_dop,\r\n rp.name AS rp_name,\r\n rp.min_memory_percent,\r\n rp.max_memory_percent,\r\n rp.min_cpu_percent,\r\n rp.max_cpu_percent,\r\n '\r\n ELSE\r\n 'sp.memory_usage + COALESCE(r.granted_query_memory, 0) AS used_memory,\r\n '\r\n END +\r\n 'LOWER(sp.status) AS status,\r\n COALESCE(r.sql_handle, sp.sql_handle) AS sql_handle,\r\n COALESCE(r.statement_start_offset, sp.statement_start_offset) AS statement_start_offset,\r\n COALESCE(r.statement_end_offset, sp.statement_end_offset) AS statement_end_offset,\r\n ' +\r\n CASE\r\n WHEN\r\n (\r\n @get_task_info <> 0\r\n OR @find_block_leaders = 1\r\n ) THEN\r\n 'sp.wait_type COLLATE Latin1_General_Bin2 AS wait_type,\r\n sp.wait_resource COLLATE Latin1_General_Bin2 AS resource_description,\r\n sp.wait_time AS wait_duration_ms,\r\n '\r\n ELSE\r\n ''\r\n END +\r\n 'NULLIF(sp.blocked, 0) AS blocking_session_id,\r\n r.plan_handle,\r\n NULLIF(r.percent_complete, 0) AS percent_complete,\r\n sp.host_name,\r\n sp.login_name,\r\n sp.program_name,\r\n s.host_process_id,\r\n COALESCE(r.text_size, s.text_size) AS text_size,\r\n COALESCE(r.language, s.language) AS language,\r\n COALESCE(r.date_format, s.date_format) AS date_format,\r\n COALESCE(r.date_first, s.date_first) AS date_first,\r\n COALESCE(r.quoted_identifier, s.quoted_identifier) AS quoted_identifier,\r\n COALESCE(r.arithabort, s.arithabort) AS arithabort,\r\n COALESCE(r.ansi_null_dflt_on, s.ansi_null_dflt_on) AS ansi_null_dflt_on,\r\n COALESCE(r.ansi_defaults, s.ansi_defaults) AS ansi_defaults,\r\n COALESCE(r.ansi_warnings, s.ansi_warnings) AS ansi_warnings,\r\n COALESCE(r.ansi_padding, s.ansi_padding) AS ansi_padding,\r\n COALESCE(r.ansi_nulls, s.ansi_nulls) AS ansi_nulls,\r\n COALESCE(r.concat_null_yields_null, s.concat_null_yields_null) AS concat_null_yields_null,\r\n COALESCE(r.transaction_isolation_level, s.transaction_isolation_level) AS transaction_isolation_level,\r\n COALESCE(r.lock_timeout, s.lock_timeout) AS lock_timeout,\r\n COALESCE(r.deadlock_priority, s.deadlock_priority) AS deadlock_priority,\r\n COALESCE(r.row_count, s.row_count) AS row_count,\r\n COALESCE(r.command, sp.cmd) AS command_type,\r\n NULLIF(COALESCE(r.context_info, s.context_info), 0x) AS context_info,\r\n COALESCE\r\n (\r\n CASE\r\n WHEN\r\n (\r\n s.is_user_process = 0\r\n AND r.total_elapsed_time >= 0\r\n ) THEN\r\n DATEADD\r\n (\r\n ms,\r\n 1000 * (DATEPART(ms, DATEADD(second, -(r.total_elapsed_time / 1000), GETDATE())) / 500) - DATEPART(ms, DATEADD(second, -(r.total_elapsed_time / 1000), GETDATE())),\r\n DATEADD(second, -(r.total_elapsed_time / 1000), GETDATE())\r\n )\r\n END,\r\n NULLIF(COALESCE(r.start_time, sp.last_request_end_time), CONVERT(DATETIME, ''19000101'', 112)),\r\n sp.login_time\r\n ) AS start_time,\r\n sp.login_time,\r\n CASE\r\n WHEN s.is_user_process = 1 THEN\r\n s.last_request_start_time\r\n ELSE\r\n COALESCE\r\n (\r\n DATEADD\r\n (\r\n ms,\r\n 1000 * (DATEPART(ms, DATEADD(second, -(r.total_elapsed_time / 1000), GETDATE())) / 500) - DATEPART(ms, DATEADD(second, -(r.total_elapsed_time / 1000), GETDATE())),\r\n DATEADD(second, -(r.total_elapsed_time / 1000), GETDATE())\r\n ),\r\n s.last_request_start_time\r\n )\r\n END AS last_request_start_time,\r\n r.transaction_id,\r\n sp.database_id,\r\n sp.open_tran_count,\r\n ' +\r\n CASE\r\n WHEN EXISTS\r\n (\r\n SELECT\r\n *\r\n FROM sys.all_columns AS ac\r\n WHERE\r\n ac.object_id = OBJECT_ID('sys.dm_exec_sessions')\r\n AND ac.name = 'group_id'\r\n )\r\n THEN 's.group_id,'\r\n ELSE 'CONVERT(INT, NULL) AS group_id,'\r\n END + '\r\n s.original_login_name\r\n FROM ' +\r\n CASE\r\n WHEN @get_memory_info = 1 THEN\r\n '(\r\n SELECT TOP(@i)\r\n rp0.*\r\n FROM sys.resource_governor_resource_pools AS rp0\r\n ) AS rp\r\n RIGHT OUTER HASH JOIN\r\n (\r\n (\r\n SELECT TOP(@i)\r\n wg0.*\r\n FROM sys.resource_governor_workload_groups AS wg0\r\n ) AS wg\r\n RIGHT OUTER HASH JOIN\r\n (\r\n (\r\n SELECT TOP(@i)\r\n rs0.*\r\n FROM sys.dm_exec_query_resource_semaphores AS rs0\r\n ) AS rs\r\n RIGHT OUTER HASH JOIN\r\n (\r\n ' + @core_session_join +\r\n 'LEFT OUTER LOOP JOIN sys.dm_exec_query_memory_grants AS mg ON\r\n sp.session_id = mg.session_id\r\n AND sp.request_id = mg.request_id\r\n ) ON\r\n rs.resource_semaphore_id = mg.resource_semaphore_id\r\n AND rs.pool_id = mg.pool_id\r\n ) ON\r\n wg.group_id = s.group_id\r\n ) ON\r\n rp.pool_id = wg.pool_id '\r\n ELSE @core_session_join\r\n END + '\r\n ) AS y\r\n ' +\r\n CASE\r\n WHEN @get_task_info = 2 THEN\r\n CONVERT(VARCHAR(MAX), '') +\r\n 'LEFT OUTER HASH JOIN\r\n (\r\n SELECT TOP(@i)\r\n task_nodes.task_node.value(''(session_id/text())[1]'', ''SMALLINT'') AS session_id,\r\n task_nodes.task_node.value(''(request_id/text())[1]'', ''INT'') AS request_id,\r\n task_nodes.task_node.value(''(physical_io/text())[1]'', ''BIGINT'') AS physical_io,\r\n task_nodes.task_node.value(''(context_switches/text())[1]'', ''BIGINT'') AS context_switches,\r\n task_nodes.task_node.value(''(tasks/text())[1]'', ''INT'') AS tasks,\r\n task_nodes.task_node.value(''(block_info/text())[1]'', ''NVARCHAR(4000)'') AS block_info,\r\n task_nodes.task_node.value(''(waits/text())[1]'', ''NVARCHAR(4000)'') AS wait_info,\r\n task_nodes.task_node.value(''(thread_CPU_snapshot/text())[1]'', ''BIGINT'') AS thread_CPU_snapshot\r\n FROM\r\n (\r\n SELECT TOP(@i)\r\n CONVERT\r\n (\r\n XML,\r\n REPLACE\r\n (\r\n CONVERT(NVARCHAR(MAX), tasks_raw.task_xml_raw) COLLATE Latin1_General_Bin2,\r\n N''</waits></tasks><tasks><waits>'',\r\n N'', ''\r\n )\r\n ) AS task_xml\r\n FROM\r\n (\r\n SELECT TOP(@i)\r\n CASE waits.r\r\n WHEN 1 THEN\r\n waits.session_id\r\n ELSE\r\n NULL\r\n END AS [session_id],\r\n CASE waits.r\r\n WHEN 1 THEN\r\n waits.request_id\r\n ELSE\r\n NULL\r\n END AS [request_id],\r\n CASE waits.r\r\n WHEN 1 THEN\r\n waits.physical_io\r\n ELSE\r\n NULL\r\n END AS [physical_io],\r\n CASE waits.r\r\n WHEN 1 THEN\r\n waits.context_switches\r\n ELSE\r\n NULL\r\n END AS [context_switches],\r\n CASE waits.r\r\n WHEN 1 THEN\r\n waits.thread_CPU_snapshot\r\n ELSE\r\n NULL\r\n END AS [thread_CPU_snapshot],\r\n CASE waits.r\r\n WHEN 1 THEN\r\n waits.tasks\r\n ELSE\r\n NULL\r\n END AS [tasks],\r\n CASE waits.r\r\n WHEN 1 THEN\r\n waits.block_info\r\n ELSE\r\n NULL\r\n END AS [block_info],\r\n REPLACE\r\n (\r\n REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\r\n REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\r\n REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\r\n CONVERT\r\n (\r\n NVARCHAR(MAX),\r\n N''('' +\r\n CONVERT(NVARCHAR, num_waits) + N''x: '' +\r\n CASE num_waits\r\n WHEN 1 THEN\r\n CONVERT(NVARCHAR, min_wait_time) + N''ms''\r\n WHEN 2 THEN\r\n CASE\r\n WHEN min_wait_time <> max_wait_time THEN\r\n CONVERT(NVARCHAR, min_wait_time) + N''/'' + CONVERT(NVARCHAR, max_wait_time) + N''ms''\r\n ELSE\r\n CONVERT(NVARCHAR, max_wait_time) + N''ms''\r\n END\r\n ELSE\r\n CASE\r\n WHEN min_wait_time <> max_wait_time THEN\r\n CONVERT(NVARCHAR, min_wait_time) + N''/'' + CONVERT(NVARCHAR, avg_wait_time) + N''/'' + CONVERT(NVARCHAR, max_wait_time) + N''ms''\r\n ELSE\r\n CONVERT(NVARCHAR, max_wait_time) + N''ms''\r\n END\r\n END +\r\n N'')'' + wait_type COLLATE Latin1_General_Bin2\r\n ),\r\n NCHAR(31),N''?''),NCHAR(30),N''?''),NCHAR(29),N''?''),NCHAR(28),N''?''),NCHAR(27),N''?''),NCHAR(26),N''?''),NCHAR(25),N''?''),NCHAR(24),N''?''),NCHAR(23),N''?''),NCHAR(22),N''?''),\r\n NCHAR(21),N''?''),NCHAR(20),N''?''),NCHAR(19),N''?''),NCHAR(18),N''?''),NCHAR(17),N''?''),NCHAR(16),N''?''),NCHAR(15),N''?''),NCHAR(14),N''?''),NCHAR(12),N''?''),\r\n NCHAR(11),N''?''),NCHAR(8),N''?''),NCHAR(7),N''?''),NCHAR(6),N''?''),NCHAR(5),N''?''),NCHAR(4),N''?''),NCHAR(3),N''?''),NCHAR(2),N''?''),NCHAR(1),N''?''),\r\n NCHAR(0),\r\n N''''\r\n ) AS [waits]\r\n FROM\r\n (\r\n SELECT TOP(@i)\r\n w1.*,\r\n ROW_NUMBER() OVER\r\n (\r\n PARTITION BY\r\n w1.session_id,\r\n w1.request_id\r\n ORDER BY\r\n w1.block_info DESC,\r\n w1.num_waits DESC,\r\n w1.wait_type\r\n ) AS r\r\n FROM\r\n (\r\n SELECT TOP(@i)\r\n task_info.session_id,\r\n task_info.request_id,\r\n task_info.physical_io,\r\n task_info.context_switches,\r\n task_info.thread_CPU_snapshot,\r\n task_info.num_tasks AS tasks,\r\n CASE\r\n WHEN task_info.runnable_time IS NOT NULL THEN\r\n ''RUNNABLE''\r\n ELSE\r\n wt2.wait_type\r\n END AS wait_type,\r\n NULLIF(COUNT(COALESCE(task_info.runnable_time, wt2.waiting_task_address)), 0) AS num_waits,\r\n MIN(COALESCE(task_info.runnable_time, wt2.wait_duration_ms)) AS min_wait_time,\r\n AVG(COALESCE(task_info.runnable_time, wt2.wait_duration_ms)) AS avg_wait_time,\r\n MAX(COALESCE(task_info.runnable_time, wt2.wait_duration_ms)) AS max_wait_time,\r\n MAX(wt2.block_info) AS block_info\r\n FROM\r\n (\r\n SELECT TOP(@i)\r\n t.session_id,\r\n t.request_id,\r\n SUM(CONVERT(BIGINT, t.pending_io_count)) OVER (PARTITION BY t.session_id, t.request_id) AS physical_io,\r\n SUM(CONVERT(BIGINT, t.context_switches_count)) OVER (PARTITION BY t.session_id, t.request_id) AS context_switches,\r\n ' +\r\n CASE\r\n WHEN\r\n @output_column_list LIKE '%|[CPU_delta|]%' ESCAPE '|'\r\n AND @sys_info = 1\r\n THEN\r\n 'SUM(tr.usermode_time + tr.kernel_time) OVER (PARTITION BY t.session_id, t.request_id) '\r\n ELSE\r\n 'CONVERT(BIGINT, NULL) '\r\n END +\r\n ' AS thread_CPU_snapshot,\r\n COUNT(*) OVER (PARTITION BY t.session_id, t.request_id) AS num_tasks,\r\n t.task_address,\r\n t.task_state,\r\n CASE\r\n WHEN\r\n t.task_state = ''RUNNABLE''\r\n AND w.runnable_time > 0 THEN\r\n w.runnable_time\r\n ELSE\r\n NULL\r\n END AS runnable_time\r\n FROM sys.dm_os_tasks AS t\r\n CROSS APPLY\r\n (\r\n SELECT TOP(1)\r\n sp2.session_id\r\n FROM @sessions AS sp2\r\n WHERE\r\n sp2.session_id = t.session_id\r\n AND sp2.request_id = t.request_id\r\n AND sp2.status <> ''sleeping''\r\n ) AS sp20\r\n LEFT OUTER HASH JOIN\r\n (\r\n ' +\r\n CASE\r\n WHEN @sys_info = 1 THEN\r\n 'SELECT TOP(@i)\r\n (\r\n SELECT TOP(@i)\r\n ms_ticks\r\n FROM sys.dm_os_sys_info\r\n ) -\r\n w0.wait_resumed_ms_ticks AS runnable_time,\r\n w0.worker_address,\r\n w0.thread_address,\r\n w0.task_bound_ms_ticks\r\n FROM sys.dm_os_workers AS w0\r\n WHERE\r\n w0.state = ''RUNNABLE''\r\n OR @first_collection_ms_ticks >= w0.task_bound_ms_ticks'\r\n ELSE\r\n 'SELECT\r\n CONVERT(BIGINT, NULL) AS runnable_time,\r\n CONVERT(VARBINARY(8), NULL) AS worker_address,\r\n CONVERT(VARBINARY(8), NULL) AS thread_address,\r\n CONVERT(BIGINT, NULL) AS task_bound_ms_ticks\r\n WHERE\r\n 1 = 0'\r\n END +\r\n '\r\n ) AS w ON\r\n w.worker_address = t.worker_address\r\n ' +\r\n CASE\r\n WHEN\r\n @output_column_list LIKE '%|[CPU_delta|]%' ESCAPE '|'\r\n AND @sys_info = 1\r\n THEN\r\n 'LEFT OUTER HASH JOIN sys.dm_os_threads AS tr ON\r\n tr.thread_address = w.thread_address\r\n AND @first_collection_ms_ticks >= w.task_bound_ms_ticks\r\n '\r\n ELSE\r\n ''\r\n END +\r\n ') AS task_info\r\n LEFT OUTER HASH JOIN\r\n (\r\n SELECT TOP(@i)\r\n wt1.wait_type,\r\n wt1.waiting_task_address,\r\n MAX(wt1.wait_duration_ms) AS wait_duration_ms,\r\n MAX(wt1.block_info) AS block_info\r\n FROM\r\n (\r\n SELECT DISTINCT TOP(@i)\r\n wt.wait_type +\r\n CASE\r\n WHEN wt.wait_type LIKE N''PAGE%LATCH_%'' THEN\r\n '':'' +\r\n COALESCE(DB_NAME(CONVERT(INT, LEFT(wt.resource_description, CHARINDEX(N'':'', wt.resource_description) - 1))), N''(null)'') +\r\n N'':'' +\r\n SUBSTRING(wt.resource_description, CHARINDEX(N'':'', wt.resource_description) + 1, LEN(wt.resource_description) - CHARINDEX(N'':'', REVERSE(wt.resource_description)) - CHARINDEX(N'':'', wt.resource_description)) +\r\n N''('' +\r\n CASE\r\n WHEN\r\n CONVERT(INT, RIGHT(wt.resource_description, CHARINDEX(N'':'', REVERSE(wt.resource_description)) - 1)) = 1 OR\r\n CONVERT(INT, RIGHT(wt.resource_description, CHARINDEX(N'':'', REVERSE(wt.resource_description)) - 1)) % 8088 = 0\r\n THEN\r\n N''PFS''\r\n WHEN\r\n CONVERT(INT, RIGHT(wt.resource_description, CHARINDEX(N'':'', REVERSE(wt.resource_description)) - 1)) = 2 OR\r\n CONVERT(INT, RIGHT(wt.resource_description, CHARINDEX(N'':'', REVERSE(wt.resource_description)) - 1)) % 511232 = 0\r\n THEN\r\n N''GAM''\r\n WHEN\r\n CONVERT(INT, RIGHT(wt.resource_description, CHARINDEX(N'':'', REVERSE(wt.resource_description)) - 1)) = 3 OR\r\n (CONVERT(INT, RIGHT(wt.resource_description, CHARINDEX(N'':'', REVERSE(wt.resource_description)) - 1)) - 1) % 511232 = 0\r\n THEN\r\n N''SGAM''\r\n WHEN\r\n CONVERT(INT, RIGHT(wt.resource_description, CHARINDEX(N'':'', REVERSE(wt.resource_description)) - 1)) = 6 OR\r\n (CONVERT(INT, RIGHT(wt.resource_description, CHARINDEX(N'':'', REVERSE(wt.resource_description)) - 1)) - 6) % 511232 = 0\r\n THEN\r\n N''DCM''\r\n WHEN\r\n CONVERT(INT, RIGHT(wt.resource_description, CHARINDEX(N'':'', REVERSE(wt.resource_description)) - 1)) = 7 OR\r\n (CONVERT(INT, RIGHT(wt.resource_description, CHARINDEX(N'':'', REVERSE(wt.resource_description)) - 1)) - 7) % 511232 = 0\r\n THEN\r\n N''BCM''\r\n ELSE\r\n N''*''\r\n END +\r\n N'')''\r\n WHEN wt.wait_type IN (N''CXPACKET'', N''CXCONSUMER'', N''CXSYNC_PORT'', N''CXSYNC_CONSUMER'') THEN\r\n N'':'' +\r\n SUBSTRING\r\n (\r\n wt.resource_description,\r\n CHARINDEX(N''nodeId'', wt.resource_description) + 7,\r\n CASE\r\n WHEN CHARINDEX(N'' '', wt.resource_description, CHARINDEX(N''nodeId'', wt.resource_description)) > 0\r\n THEN CHARINDEX(N'' '', wt.resource_description, CHARINDEX(N''nodeId'', wt.resource_description) + 7) - 7 - CHARINDEX(N''nodeId'', wt.resource_description)\r\n ELSE 4\r\n END\r\n )\r\n WHEN wt.wait_type LIKE N''LATCH[_]%'' THEN\r\n N'' ['' + LEFT(wt.resource_description, COALESCE(NULLIF(CHARINDEX(N'' '', wt.resource_description), 0), LEN(wt.resource_description) + 1) - 1) + N'']''\r\n ELSE\r\n N''''\r\n END COLLATE Latin1_General_Bin2 AS wait_type,\r\n CASE\r\n WHEN\r\n (\r\n wt.blocking_session_id IS NOT NULL\r\n AND wt.wait_type LIKE N''LCK[_]%''\r\n ) THEN\r\n (\r\n SELECT TOP(@i)\r\n x.lock_type,\r\n REPLACE\r\n (\r\n REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\r\n REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\r\n REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\r\n DB_NAME\r\n (\r\n CONVERT\r\n (\r\n INT,\r\n SUBSTRING(wt.resource_description, NULLIF(CHARINDEX(N''dbid='', wt.resource_description), 0) + 5, COALESCE(NULLIF(CHARINDEX(N'' '', wt.resource_description, CHARINDEX(N''dbid='', wt.resource_description) + 5), 0), LEN(wt.resource_description) + 1) - CHARINDEX(N''dbid='', wt.resource_description) - 5)\r\n )\r\n ),\r\n NCHAR(31),N''?''),NCHAR(30),N''?''),NCHAR(29),N''?''),NCHAR(28),N''?''),NCHAR(27),N''?''),NCHAR(26),N''?''),NCHAR(25),N''?''),NCHAR(24),N''?''),NCHAR(23),N''?''),NCHAR(22),N''?''),\r\n NCHAR(21),N''?''),NCHAR(20),N''?''),NCHAR(19),N''?''),NCHAR(18),N''?''),NCHAR(17),N''?''),NCHAR(16),N''?''),NCHAR(15),N''?''),NCHAR(14),N''?''),NCHAR(12),N''?''),\r\n NCHAR(11),N''?''),NCHAR(8),N''?''),NCHAR(7),N''?''),NCHAR(6),N''?''),NCHAR(5),N''?''),NCHAR(4),N''?''),NCHAR(3),N''?''),NCHAR(2),N''?''),NCHAR(1),N''?''),\r\n NCHAR(0),\r\n N''''\r\n ) AS database_name,\r\n CASE x.lock_type\r\n WHEN N''objectlock'' THEN\r\n SUBSTRING(wt.resource_description, NULLIF(CHARINDEX(N''objid='', wt.resource_description), 0) + 6, COALESCE(NULLIF(CHARINDEX(N'' '', wt.resource_description, CHARINDEX(N''objid='', wt.resource_description) + 6), 0), LEN(wt.resource_description) + 1) - CHARINDEX(N''objid='', wt.resource_description) - 6)\r\n ELSE\r\n NULL\r\n END AS object_id,\r\n CASE x.lock_type\r\n WHEN N''filelock'' THEN\r\n SUBSTRING(wt.resource_description, NULLIF(CHARINDEX(N''fileid='', wt.resource_description), 0) + 7, COALESCE(NULLIF(CHARINDEX(N'' '', wt.resource_description, CHARINDEX(N''fileid='', wt.resource_description) + 7), 0), LEN(wt.resource_description) + 1) - CHARINDEX(N''fileid='', wt.resource_description) - 7)\r\n ELSE\r\n NULL\r\n END AS file_id,\r\n CASE\r\n WHEN x.lock_type in (N''pagelock'', N''extentlock'', N''ridlock'') THEN\r\n SUBSTRING(wt.resource_description, NULLIF(CHARINDEX(N''associatedObjectId='', wt.resource_description), 0) + 19, COALESCE(NULLIF(CHARINDEX(N'' '', wt.resource_description, CHARINDEX(N''associatedObjectId='', wt.resource_description) + 19), 0), LEN(wt.resource_description) + 1) - CHARINDEX(N''associatedObjectId='', wt.resource_description) - 19)\r\n WHEN x.lock_type in (N''keylock'', N''hobtlock'', N''allocunitlock'') THEN\r\n SUBSTRING(wt.resource_description, NULLIF(CHARINDEX(N''hobtid='', wt.resource_description), 0) + 7, COALESCE(NULLIF(CHARINDEX(N'' '', wt.resource_description, CHARINDEX(N''hobtid='', wt.resource_description) + 7), 0), LEN(wt.resource_description) + 1) - CHARINDEX(N''hobtid='', wt.resource_description) - 7)\r\n ELSE\r\n NULL\r\n END AS hobt_id,\r\n CASE x.lock_type\r\n WHEN N''applicationlock'' THEN\r\n SUBSTRING(wt.resource_description, NULLIF(CHARINDEX(N''hash='', wt.resource_description), 0) + 5, COALESCE(NULLIF(CHARINDEX(N'' '', wt.resource_description, CHARINDEX(N''hash='', wt.resource_description) + 5), 0), LEN(wt.resource_description) + 1) - CHARINDEX(N''hash='', wt.resource_description) - 5)\r\n ELSE\r\n NULL\r\n END AS applock_hash,\r\n CASE x.lock_type\r\n WHEN N''metadatalock'' THEN\r\n SUBSTRING(wt.resource_description, NULLIF(CHARINDEX(N''subresource='', wt.resource_description), 0) + 12, COALESCE(NULLIF(CHARINDEX(N'' '', wt.resource_description, CHARINDEX(N''subresource='', wt.resource_description) + 12), 0), LEN(wt.resource_description) + 1) - CHARINDEX(N''subresource='', wt.resource_description) - 12)\r\n ELSE\r\n NULL\r\n END AS metadata_resource,\r\n CASE x.lock_type\r\n WHEN N''metadatalock'' THEN\r\n SUBSTRING(wt.resource_description, NULLIF(CHARINDEX(N''classid='', wt.resource_description), 0) + 8, COALESCE(NULLIF(CHARINDEX(N'' dbid='', wt.resource_description) - CHARINDEX(N''classid='', wt.resource_description), 0), LEN(wt.resource_description) + 1) - 8)\r\n ELSE\r\n NULL\r\n END AS metadata_class_id\r\n FROM\r\n (\r\n SELECT TOP(1)\r\n LEFT(wt.resource_description, CHARINDEX(N'' '', wt.resource_description) - 1) COLLATE Latin1_General_Bin2 AS lock_type\r\n ) AS x\r\n FOR XML\r\n PATH('''')\r\n )\r\n ELSE NULL\r\n END AS block_info,\r\n wt.wait_duration_ms,\r\n wt.waiting_task_address\r\n FROM\r\n (\r\n SELECT TOP(@i)\r\n wt0.wait_type COLLATE Latin1_General_Bin2 AS wait_type,\r\n LEFT\r\n (\r\n p.resource_description,\r\n ISNULL(NULLIF(CHARINDEX('' (LATCH '', p.resource_description) - 1, -1), 256)\r\n ) AS resource_description,\r\n wt0.wait_duration_ms,\r\n wt0.waiting_task_address,\r\n CASE\r\n WHEN wt0.blocking_session_id = p.blocked THEN\r\n wt0.blocking_session_id\r\n ELSE\r\n NULL\r\n END AS blocking_session_id\r\n FROM sys.dm_os_waiting_tasks AS wt0\r\n CROSS APPLY\r\n (\r\n SELECT TOP(1)\r\n s0.blocked,\r\n wt0.resource_description COLLATE Latin1_General_Bin2 AS resource_description\r\n FROM @sessions AS s0\r\n WHERE\r\n s0.session_id = wt0.session_id\r\n AND COALESCE(s0.wait_type, N'''') <> N''OLEDB''\r\n AND wt0.wait_type <> N''OLEDB''\r\n ) AS p\r\n ) AS wt\r\n ) AS wt1\r\n GROUP BY\r\n wt1.wait_type,\r\n wt1.waiting_task_address\r\n ) AS wt2 ON\r\n wt2.waiting_task_address = task_info.task_address\r\n AND wt2.wait_duration_ms > 0\r\n AND task_info.runnable_time IS NULL\r\n GROUP BY\r\n task_info.session_id,\r\n task_info.request_id,\r\n task_info.physical_io,\r\n task_info.context_switches,\r\n task_info.thread_CPU_snapshot,\r\n task_info.num_tasks,\r\n CASE\r\n WHEN task_info.runnable_time IS NOT NULL THEN\r\n ''RUNNABLE''\r\n ELSE\r\n wt2.wait_type\r\n END\r\n ) AS w1\r\n ) AS waits\r\n ORDER BY\r\n waits.session_id,\r\n waits.request_id,\r\n waits.r\r\n FOR XML\r\n PATH(N''tasks''),\r\n TYPE\r\n ) AS tasks_raw (task_xml_raw)\r\n ) AS tasks_final\r\n CROSS APPLY tasks_final.task_xml.nodes(N''/tasks'') AS task_nodes (task_node)\r\n WHERE\r\n task_nodes.task_node.exist(N''session_id'') = 1\r\n ) AS tasks ON\r\n tasks.session_id = y.session_id\r\n AND tasks.request_id = y.request_id\r\n '\r\n ELSE\r\n ''\r\n END +\r\n 'LEFT OUTER HASH JOIN\r\n (\r\n SELECT TOP(@i)\r\n t_info.session_id,\r\n COALESCE(t_info.request_id, -1) AS request_id,\r\n SUM(t_info.tempdb_allocations) AS tempdb_allocations,\r\n SUM(t_info.tempdb_current) AS tempdb_current\r\n FROM\r\n (\r\n SELECT TOP(@i)\r\n tsu.session_id,\r\n tsu.request_id,\r\n tsu.user_objects_alloc_page_count +\r\n tsu.internal_objects_alloc_page_count AS tempdb_allocations,\r\n tsu.user_objects_alloc_page_count +\r\n tsu.internal_objects_alloc_page_count -\r\n tsu.user_objects_dealloc_page_count -\r\n tsu.internal_objects_dealloc_page_count AS tempdb_current\r\n FROM sys.dm_db_task_space_usage AS tsu\r\n CROSS APPLY\r\n (\r\n SELECT TOP(1)\r\n s0.session_id\r\n FROM @sessions AS s0\r\n WHERE\r\n s0.session_id = tsu.session_id\r\n ) AS p\r\n\r\n UNION ALL\r\n\r\n SELECT TOP(@i)\r\n ssu.session_id,\r\n NULL AS request_id,\r\n ssu.user_objects_alloc_page_count +\r\n ssu.internal_objects_alloc_page_count AS tempdb_allocations,\r\n ssu.user_objects_alloc_page_count +\r\n ssu.internal_objects_alloc_page_count -\r\n ssu.user_objects_dealloc_page_count -\r\n ssu.internal_objects_dealloc_page_count AS tempdb_current\r\n FROM sys.dm_db_session_space_usage AS ssu\r\n CROSS APPLY\r\n (\r\n SELECT TOP(1)\r\n s0.session_id\r\n FROM @sessions AS s0\r\n WHERE\r\n s0.session_id = ssu.session_id\r\n ) AS p\r\n ) AS t_info\r\n GROUP BY\r\n t_info.session_id,\r\n COALESCE(t_info.request_id, -1)\r\n ) AS tempdb_info ON\r\n tempdb_info.session_id = y.session_id\r\n AND tempdb_info.request_id =\r\n CASE\r\n WHEN y.status = N''sleeping'' THEN\r\n -1\r\n ELSE\r\n y.request_id\r\n END\r\n ' +\r\n CASE\r\n WHEN\r\n NOT\r\n (\r\n @get_avg_time = 1\r\n AND @recursion = 1\r\n ) THEN\r\n ''\r\n ELSE\r\n 'LEFT OUTER HASH JOIN\r\n (\r\n SELECT TOP(@i)\r\n *\r\n FROM sys.dm_exec_query_stats\r\n ) AS qs ON\r\n qs.sql_handle = y.sql_handle\r\n AND qs.plan_handle = y.plan_handle\r\n AND qs.statement_start_offset = y.statement_start_offset\r\n AND qs.statement_end_offset = y.statement_end_offset\r\n '\r\n END +\r\n ') AS x\r\n OPTION (KEEPFIXED PLAN, OPTIMIZE FOR (@i = 1)); ';\r\n\r\n SET @sql_n = CONVERT(NVARCHAR(MAX), @sql);\r\n\r\n SET @last_collection_start = GETDATE();\r\n\r\n IF\r\n @recursion = -1\r\n AND @sys_info = 1\r\n BEGIN;\r\n SELECT\r\n @first_collection_ms_ticks = ms_ticks\r\n FROM sys.dm_os_sys_info;\r\n END;\r\n\r\n INSERT #sessions\r\n (\r\n recursion,\r\n session_id,\r\n request_id,\r\n session_number,\r\n elapsed_time,\r\n avg_elapsed_time,\r\n physical_io,\r\n reads,\r\n physical_reads,\r\n writes,\r\n tempdb_allocations,\r\n tempdb_current,\r\n CPU,\r\n thread_CPU_snapshot,\r\n context_switches,\r\n used_memory,\r\n max_used_memory,\r\n requested_memory,\r\n granted_memory,\r\n tasks,\r\n status,\r\n wait_info,\r\n transaction_id,\r\n open_tran_count,\r\n sql_handle,\r\n statement_start_offset,\r\n statement_end_offset, \r\n sql_text,\r\n plan_handle,\r\n blocking_session_id,\r\n percent_complete,\r\n host_name,\r\n login_name,\r\n database_name,\r\n program_name,\r\n additional_info,\r\n memory_info,\r\n start_time,\r\n login_time,\r\n last_request_start_time\r\n )\r\n EXEC sp_executesql\r\n @sql_n,\r\n N'@recursion SMALLINT, @filter sysname, @not_filter sysname, @first_collection_ms_ticks BIGINT',\r\n @recursion, @filter, @not_filter, @first_collection_ms_ticks;\r\n\r\n --Collect transaction information?\r\n IF\r\n @recursion = 1\r\n AND\r\n (\r\n @output_column_list LIKE '%|[tran_start_time|]%' ESCAPE '|'\r\n OR @output_column_list LIKE '%|[tran_log_writes|]%' ESCAPE '|'\r\n OR @output_column_list LIKE '%|[implicit_tran|]%' ESCAPE '|'\r\n )\r\n BEGIN; \r\n DECLARE @i INT;\r\n SET @i = 2147483647;\r\n\r\n UPDATE s\r\n SET\r\n tran_start_time =\r\n CONVERT\r\n (\r\n DATETIME,\r\n LEFT\r\n (\r\n x.trans_info,\r\n NULLIF(CHARINDEX(NCHAR(254) COLLATE Latin1_General_Bin2, x.trans_info) - 1, -1)\r\n ),\r\n 121\r\n ),\r\n tran_log_writes =\r\n RIGHT\r\n (\r\n x.trans_info,\r\n LEN(x.trans_info) - CHARINDEX(NCHAR(254) COLLATE Latin1_General_Bin2, x.trans_info)\r\n ),\r\n implicit_tran =\r\n CASE\r\n WHEN x.implicit_tran = 1 THEN 'ON'\r\n ELSE 'OFF'\r\n END\r\n FROM\r\n (\r\n SELECT TOP(@i)\r\n trans_nodes.trans_node.value('(session_id/text())[1]', 'SMALLINT') AS session_id,\r\n COALESCE(trans_nodes.trans_node.value('(request_id/text())[1]', 'INT'), 0) AS request_id,\r\n trans_nodes.trans_node.value('(implicit_tran/text())[1]', 'INT') AS implicit_tran,\r\n trans_nodes.trans_node.value('(trans_info/text())[1]', 'NVARCHAR(4000)') AS trans_info\r\n FROM\r\n (\r\n SELECT TOP(@i)\r\n CONVERT\r\n (\r\n XML,\r\n REPLACE\r\n (\r\n CONVERT(NVARCHAR(MAX), trans_raw.trans_xml_raw) COLLATE Latin1_General_Bin2,\r\n N'</trans_info></trans><trans><trans_info>', N''\r\n )\r\n )\r\n FROM\r\n (\r\n SELECT TOP(@i)\r\n CASE u_trans.r\r\n WHEN 1 THEN u_trans.session_id\r\n ELSE NULL\r\n END AS [session_id],\r\n CASE u_trans.r\r\n WHEN 1 THEN u_trans.request_id\r\n ELSE NULL\r\n END AS [request_id],\r\n u_trans.implicit_tran AS [implicit_tran],\r\n CONVERT\r\n (\r\n NVARCHAR(MAX),\r\n CASE\r\n WHEN u_trans.database_id IS NOT NULL THEN\r\n CASE u_trans.r\r\n WHEN 1 THEN COALESCE(CONVERT(NVARCHAR, u_trans.transaction_start_time, 121) + NCHAR(254), N'')\r\n ELSE N''\r\n END +\r\n REPLACE\r\n (\r\n REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\r\n REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\r\n REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\r\n CONVERT(VARCHAR(128), COALESCE(DB_NAME(u_trans.database_id), N'(null)')),\r\n NCHAR(31),N'?'),NCHAR(30),N'?'),NCHAR(29),N'?'),NCHAR(28),N'?'),NCHAR(27),N'?'),NCHAR(26),N'?'),NCHAR(25),N'?'),NCHAR(24),N'?'),NCHAR(23),N'?'),NCHAR(22),N'?'),\r\n NCHAR(21),N'?'),NCHAR(20),N'?'),NCHAR(19),N'?'),NCHAR(18),N'?'),NCHAR(17),N'?'),NCHAR(16),N'?'),NCHAR(15),N'?'),NCHAR(14),N'?'),NCHAR(12),N'?'),\r\n NCHAR(11),N'?'),NCHAR(8),N'?'),NCHAR(7),N'?'),NCHAR(6),N'?'),NCHAR(5),N'?'),NCHAR(4),N'?'),NCHAR(3),N'?'),NCHAR(2),N'?'),NCHAR(1),N'?'),\r\n NCHAR(0),\r\n N'?'\r\n ) +\r\n N': ' +\r\n CONVERT(NVARCHAR, u_trans.log_record_count) + N' (' + CONVERT(NVARCHAR, u_trans.log_kb_used) + N' kB)' +\r\n N','\r\n ELSE\r\n N'N/A,'\r\n END COLLATE Latin1_General_Bin2\r\n ) AS [trans_info]\r\n FROM\r\n (\r\n SELECT TOP(@i)\r\n trans.*,\r\n ROW_NUMBER() OVER\r\n (\r\n PARTITION BY\r\n trans.session_id,\r\n trans.request_id\r\n ORDER BY\r\n trans.transaction_start_time DESC\r\n ) AS r\r\n FROM\r\n (\r\n SELECT TOP(@i)\r\n session_tran_map.session_id,\r\n session_tran_map.request_id,\r\n s_tran.database_id,\r\n COALESCE(SUM(s_tran.database_transaction_log_record_count), 0) AS log_record_count,\r\n COALESCE(SUM(s_tran.database_transaction_log_bytes_used), 0) / 1024 AS log_kb_used,\r\n MIN(s_tran.database_transaction_begin_time) AS transaction_start_time,\r\n MAX\r\n (\r\n CASE\r\n WHEN a_tran.name = 'implicit_transaction' THEN 1\r\n ELSE 0\r\n END\r\n ) AS implicit_tran\r\n FROM\r\n (\r\n SELECT TOP(@i)\r\n *\r\n FROM sys.dm_tran_active_transactions\r\n WHERE\r\n transaction_begin_time <= @last_collection_start\r\n ) AS a_tran\r\n INNER HASH JOIN\r\n (\r\n SELECT TOP(@i)\r\n *\r\n FROM sys.dm_tran_database_transactions\r\n WHERE\r\n database_id < 32767\r\n ) AS s_tran ON\r\n s_tran.transaction_id = a_tran.transaction_id\r\n LEFT OUTER HASH JOIN\r\n (\r\n SELECT TOP(@i)\r\n *\r\n FROM sys.dm_tran_session_transactions\r\n ) AS tst ON\r\n s_tran.transaction_id = tst.transaction_id\r\n CROSS APPLY\r\n (\r\n SELECT TOP(1)\r\n s3.session_id,\r\n s3.request_id\r\n FROM\r\n (\r\n SELECT TOP(1)\r\n s1.session_id,\r\n s1.request_id\r\n FROM #sessions AS s1\r\n WHERE\r\n s1.transaction_id = s_tran.transaction_id\r\n AND s1.recursion = 1\r\n \r\n UNION ALL\r\n \r\n SELECT TOP(1)\r\n s2.session_id,\r\n s2.request_id\r\n FROM #sessions AS s2\r\n WHERE\r\n s2.session_id = tst.session_id\r\n AND s2.recursion = 1\r\n ) AS s3\r\n ORDER BY\r\n s3.request_id\r\n ) AS session_tran_map\r\n GROUP BY\r\n session_tran_map.session_id,\r\n session_tran_map.request_id,\r\n s_tran.database_id\r\n ) AS trans\r\n ) AS u_trans\r\n FOR XML\r\n PATH('trans'),\r\n TYPE\r\n ) AS trans_raw (trans_xml_raw)\r\n ) AS trans_final (trans_xml)\r\n CROSS APPLY trans_final.trans_xml.nodes('/trans') AS trans_nodes (trans_node)\r\n ) AS x\r\n INNER HASH JOIN #sessions AS s ON\r\n s.session_id = x.session_id\r\n AND s.request_id = x.request_id\r\n OPTION (OPTIMIZE FOR (@i = 1));\r\n END;\r\n\r\n --Variables for text and plan collection\r\n DECLARE \r\n @session_id SMALLINT,\r\n @request_id INT,\r\n @sql_handle VARBINARY(64),\r\n @plan_handle VARBINARY(64),\r\n @statement_start_offset INT,\r\n @statement_end_offset INT,\r\n @start_time DATETIME,\r\n @database_name sysname;\r\n\r\n IF\r\n @recursion = 1\r\n AND @output_column_list LIKE '%|[sql_text|]%' ESCAPE '|'\r\n BEGIN;\r\n DECLARE sql_cursor\r\n CURSOR LOCAL FAST_FORWARD\r\n FOR\r\n SELECT\r\n session_id,\r\n request_id,\r\n sql_handle,\r\n statement_start_offset,\r\n statement_end_offset\r\n FROM #sessions\r\n WHERE\r\n recursion = 1\r\n AND sql_handle IS NOT NULL\r\n OPTION (KEEPFIXED PLAN);\r\n\r\n OPEN sql_cursor;\r\n\r\n FETCH NEXT FROM sql_cursor\r\n INTO\r\n @session_id,\r\n @request_id,\r\n @sql_handle,\r\n @statement_start_offset,\r\n @statement_end_offset;\r\n\r\n --Wait up to 5 ms for the SQL text, then give up\r\n SET LOCK_TIMEOUT 5;\r\n\r\n WHILE @@FETCH_STATUS = 0\r\n BEGIN;\r\n BEGIN TRY;\r\n UPDATE s\r\n SET\r\n s.sql_text =\r\n (\r\n SELECT\r\n REPLACE\r\n (\r\n REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\r\n REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\r\n REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\r\n N'--' + NCHAR(13) + NCHAR(10) +\r\n CASE\r\n WHEN @get_full_inner_text = 1 THEN est.text\r\n WHEN LEN(est.text) < (@statement_end_offset / 2) + 1 THEN est.text\r\n WHEN SUBSTRING(est.text, (@statement_start_offset/2), 2) LIKE N'[a-zA-Z0-9][a-zA-Z0-9]' THEN est.text\r\n ELSE\r\n CASE\r\n WHEN @statement_start_offset > 0 THEN\r\n SUBSTRING\r\n (\r\n est.text,\r\n ((@statement_start_offset/2) + 1),\r\n (\r\n CASE\r\n WHEN @statement_end_offset = -1 THEN 2147483647\r\n ELSE ((@statement_end_offset - @statement_start_offset)/2) + 1\r\n END\r\n )\r\n )\r\n ELSE RTRIM(LTRIM(est.text))\r\n END\r\n END +\r\n NCHAR(13) + NCHAR(10) + N'--' COLLATE Latin1_General_Bin2,\r\n NCHAR(31),N'?'),NCHAR(30),N'?'),NCHAR(29),N'?'),NCHAR(28),N'?'),NCHAR(27),N'?'),NCHAR(26),N'?'),NCHAR(25),N'?'),NCHAR(24),N'?'),NCHAR(23),N'?'),NCHAR(22),N'?'),\r\n NCHAR(21),N'?'),NCHAR(20),N'?'),NCHAR(19),N'?'),NCHAR(18),N'?'),NCHAR(17),N'?'),NCHAR(16),N'?'),NCHAR(15),N'?'),NCHAR(14),N'?'),NCHAR(12),N'?'),\r\n NCHAR(11),N'?'),NCHAR(8),N'?'),NCHAR(7),N'?'),NCHAR(6),N'?'),NCHAR(5),N'?'),NCHAR(4),N'?'),NCHAR(3),N'?'),NCHAR(2),N'?'),NCHAR(1),N'?'),\r\n NCHAR(0),\r\n N''\r\n ) AS [processing-instruction(query)]\r\n FOR XML\r\n PATH(''),\r\n TYPE\r\n ),\r\n s.statement_start_offset =\r\n CASE\r\n WHEN LEN(est.text) < (@statement_end_offset / 2) + 1 THEN 0\r\n WHEN SUBSTRING(CONVERT(VARCHAR(MAX), est.text), (@statement_start_offset/2), 2) LIKE '[a-zA-Z0-9][a-zA-Z0-9]' THEN 0\r\n ELSE @statement_start_offset\r\n END,\r\n s.statement_end_offset =\r\n CASE\r\n WHEN LEN(est.text) < (@statement_end_offset / 2) + 1 THEN -1\r\n WHEN SUBSTRING(CONVERT(VARCHAR(MAX), est.text), (@statement_start_offset/2), 2) LIKE '[a-zA-Z0-9][a-zA-Z0-9]' THEN -1\r\n ELSE @statement_end_offset\r\n END\r\n FROM\r\n #sessions AS s,\r\n (\r\n SELECT TOP(1)\r\n text\r\n FROM\r\n (\r\n SELECT\r\n text,\r\n 0 AS row_num\r\n FROM sys.dm_exec_sql_text(@sql_handle)\r\n \r\n UNION ALL\r\n \r\n SELECT\r\n NULL,\r\n 1 AS row_num\r\n ) AS est0\r\n ORDER BY\r\n row_num\r\n ) AS est\r\n WHERE\r\n s.session_id = @session_id\r\n AND s.request_id = @request_id\r\n AND s.recursion = 1\r\n OPTION (KEEPFIXED PLAN);\r\n END TRY\r\n BEGIN CATCH;\r\n UPDATE s\r\n SET\r\n s.sql_text =\r\n CASE ERROR_NUMBER()\r\n WHEN 1222 THEN '<timeout_exceeded />'\r\n ELSE '<error message=\"' + ERROR_MESSAGE() + '\" />'\r\n END\r\n FROM #sessions AS s\r\n WHERE\r\n s.session_id = @session_id\r\n AND s.request_id = @request_id\r\n AND s.recursion = 1\r\n OPTION (KEEPFIXED PLAN);\r\n END CATCH;\r\n\r\n FETCH NEXT FROM sql_cursor\r\n INTO\r\n @session_id,\r\n @request_id,\r\n @sql_handle,\r\n @statement_start_offset,\r\n @statement_end_offset;\r\n END;\r\n\r\n --Return this to the default\r\n SET LOCK_TIMEOUT -1;\r\n\r\n CLOSE sql_cursor;\r\n DEALLOCATE sql_cursor;\r\n END;\r\n\r\n IF\r\n @get_outer_command = 1\r\n AND @recursion = 1\r\n AND @output_column_list LIKE '%|[sql_command|]%' ESCAPE '|'\r\n BEGIN;\r\n DECLARE @buffer_results TABLE\r\n (\r\n EventType VARCHAR(30),\r\n Parameters INT,\r\n EventInfo NVARCHAR(4000),\r\n start_time DATETIME,\r\n session_number INT IDENTITY(1,1) NOT NULL PRIMARY KEY\r\n );\r\n\r\n DECLARE buffer_cursor\r\n CURSOR LOCAL FAST_FORWARD\r\n FOR\r\n SELECT\r\n session_id,\r\n MAX(start_time) AS start_time\r\n FROM #sessions\r\n WHERE\r\n recursion = 1\r\n GROUP BY\r\n session_id\r\n ORDER BY\r\n session_id\r\n OPTION (KEEPFIXED PLAN);\r\n\r\n OPEN buffer_cursor;\r\n\r\n FETCH NEXT FROM buffer_cursor\r\n INTO\r\n @session_id,\r\n @start_time;\r\n\r\n WHILE @@FETCH_STATUS = 0\r\n BEGIN;\r\n BEGIN TRY;\r\n --In SQL Server 2008, DBCC INPUTBUFFER will throw\r\n --an exception if the session no longer exists\r\n INSERT @buffer_results\r\n (\r\n EventType,\r\n Parameters,\r\n EventInfo\r\n )\r\n EXEC sp_executesql\r\n N'DBCC INPUTBUFFER(@session_id) WITH NO_INFOMSGS;',\r\n N'@session_id SMALLINT',\r\n @session_id;\r\n\r\n UPDATE br\r\n SET\r\n br.start_time = @start_time\r\n FROM @buffer_results AS br\r\n WHERE\r\n br.session_number =\r\n (\r\n SELECT MAX(br2.session_number)\r\n FROM @buffer_results br2\r\n );\r\n END TRY\r\n BEGIN CATCH\r\n END CATCH;\r\n\r\n FETCH NEXT FROM buffer_cursor\r\n INTO\r\n @session_id,\r\n @start_time;\r\n END;\r\n\r\n UPDATE s\r\n SET\r\n sql_command =\r\n (\r\n SELECT\r\n REPLACE\r\n (\r\n REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\r\n REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\r\n REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\r\n CONVERT\r\n (\r\n NVARCHAR(MAX),\r\n N'--' + NCHAR(13) + NCHAR(10) + br.EventInfo + NCHAR(13) + NCHAR(10) + N'--' COLLATE Latin1_General_Bin2\r\n ),\r\n NCHAR(31),N'?'),NCHAR(30),N'?'),NCHAR(29),N'?'),NCHAR(28),N'?'),NCHAR(27),N'?'),NCHAR(26),N'?'),NCHAR(25),N'?'),NCHAR(24),N'?'),NCHAR(23),N'?'),NCHAR(22),N'?'),\r\n NCHAR(21),N'?'),NCHAR(20),N'?'),NCHAR(19),N'?'),NCHAR(18),N'?'),NCHAR(17),N'?'),NCHAR(16),N'?'),NCHAR(15),N'?'),NCHAR(14),N'?'),NCHAR(12),N'?'),\r\n NCHAR(11),N'?'),NCHAR(8),N'?'),NCHAR(7),N'?'),NCHAR(6),N'?'),NCHAR(5),N'?'),NCHAR(4),N'?'),NCHAR(3),N'?'),NCHAR(2),N'?'),NCHAR(1),N'?'),\r\n NCHAR(0),\r\n N''\r\n ) AS [processing-instruction(query)]\r\n FROM @buffer_results AS br\r\n WHERE\r\n br.session_number = s.session_number\r\n AND br.start_time = s.start_time\r\n AND\r\n (\r\n (\r\n s.start_time = s.last_request_start_time\r\n AND EXISTS\r\n (\r\n SELECT *\r\n FROM sys.dm_exec_requests r2\r\n WHERE\r\n r2.session_id = s.session_id\r\n AND r2.request_id = s.request_id\r\n AND r2.start_time = s.start_time\r\n )\r\n )\r\n OR\r\n (\r\n s.request_id = 0\r\n AND EXISTS\r\n (\r\n SELECT *\r\n FROM sys.dm_exec_sessions s2\r\n WHERE\r\n s2.session_id = s.session_id\r\n AND s2.last_request_start_time = s.last_request_start_time\r\n )\r\n )\r\n )\r\n FOR XML\r\n PATH(''),\r\n TYPE\r\n )\r\n FROM #sessions AS s\r\n WHERE\r\n recursion = 1\r\n OPTION (KEEPFIXED PLAN);\r\n\r\n CLOSE buffer_cursor;\r\n DEALLOCATE buffer_cursor;\r\n END;\r\n\r\n IF\r\n @get_plans >= 1\r\n AND @recursion = 1\r\n AND @output_column_list LIKE '%|[query_plan|]%' ESCAPE '|'\r\n BEGIN;\r\n DECLARE @live_plan BIT;\r\n SET @live_plan = ISNULL(CONVERT(BIT, SIGN(OBJECT_ID('sys.dm_exec_query_statistics_xml'))), 0)\r\n\r\n DECLARE plan_cursor\r\n CURSOR LOCAL FAST_FORWARD\r\n FOR\r\n SELECT\r\n session_id,\r\n request_id,\r\n plan_handle,\r\n statement_start_offset,\r\n statement_end_offset\r\n FROM #sessions\r\n WHERE\r\n recursion = 1\r\n AND plan_handle IS NOT NULL\r\n OPTION (KEEPFIXED PLAN);\r\n\r\n OPEN plan_cursor;\r\n\r\n FETCH NEXT FROM plan_cursor\r\n INTO\r\n @session_id,\r\n @request_id,\r\n @plan_handle,\r\n @statement_start_offset,\r\n @statement_end_offset;\r\n\r\n --Wait up to 5 ms for a query plan, then give up\r\n SET LOCK_TIMEOUT 5;\r\n\r\n WHILE @@FETCH_STATUS = 0\r\n BEGIN;\r\n DECLARE @query_plan XML;\r\n SET @query_plan = NULL;\r\n\r\n IF @live_plan = 1\r\n BEGIN;\r\n BEGIN TRY;\r\n SELECT\r\n @query_plan = x.query_plan\r\n FROM sys.dm_exec_query_statistics_xml(@session_id) AS x;\r\n\r\n IF\r\n @query_plan IS NOT NULL\r\n AND EXISTS\r\n (\r\n SELECT\r\n *\r\n FROM sys.dm_exec_requests AS r\r\n WHERE\r\n r.session_id = @session_id\r\n AND r.request_id = @request_id\r\n AND r.plan_handle = @plan_handle\r\n AND r.statement_start_offset = @statement_start_offset\r\n AND r.statement_end_offset = @statement_end_offset\r\n )\r\n BEGIN;\r\n UPDATE s\r\n SET\r\n s.query_plan = @query_plan\r\n FROM #sessions AS s\r\n WHERE\r\n s.session_id = @session_id\r\n AND s.request_id = @request_id\r\n AND s.recursion = 1\r\n OPTION (KEEPFIXED PLAN);\r\n END;\r\n END TRY\r\n BEGIN CATCH;\r\n SET @query_plan = NULL;\r\n END CATCH;\r\n END;\r\n\r\n IF @query_plan IS NULL\r\n BEGIN;\r\n BEGIN TRY;\r\n UPDATE s\r\n SET\r\n s.query_plan =\r\n (\r\n SELECT\r\n CONVERT(xml, query_plan)\r\n FROM sys.dm_exec_text_query_plan\r\n (\r\n @plan_handle,\r\n CASE @get_plans\r\n WHEN 1 THEN\r\n @statement_start_offset\r\n ELSE\r\n 0\r\n END,\r\n CASE @get_plans\r\n WHEN 1 THEN\r\n @statement_end_offset\r\n ELSE\r\n -1\r\n END\r\n )\r\n )\r\n FROM #sessions AS s\r\n WHERE\r\n s.session_id = @session_id\r\n AND s.request_id = @request_id\r\n AND s.recursion = 1\r\n OPTION (KEEPFIXED PLAN);\r\n END TRY\r\n BEGIN CATCH;\r\n IF ERROR_NUMBER() = 6335\r\n BEGIN;\r\n UPDATE s\r\n SET\r\n s.query_plan =\r\n (\r\n SELECT\r\n N'--' + NCHAR(13) + NCHAR(10) +\r\n N'-- Could not render showplan due to XML data type limitations. ' + NCHAR(13) + NCHAR(10) +\r\n N'-- To see the graphical plan save the XML below as a .SQLPLAN file and re-open in SSMS.' + NCHAR(13) + NCHAR(10) +\r\n N'--' + NCHAR(13) + NCHAR(10) +\r\n REPLACE(qp.query_plan, N'<RelOp', NCHAR(13)+NCHAR(10)+N'<RelOp') +\r\n NCHAR(13) + NCHAR(10) + N'--' COLLATE Latin1_General_Bin2 AS [processing-instruction(query_plan)]\r\n FROM sys.dm_exec_text_query_plan\r\n (\r\n @plan_handle,\r\n CASE @get_plans\r\n WHEN 1 THEN\r\n @statement_start_offset\r\n ELSE\r\n 0\r\n END,\r\n CASE @get_plans\r\n WHEN 1 THEN\r\n @statement_end_offset\r\n ELSE\r\n -1\r\n END\r\n ) AS qp\r\n FOR XML\r\n PATH(''),\r\n TYPE\r\n )\r\n FROM #sessions AS s\r\n WHERE\r\n s.session_id = @session_id\r\n AND s.request_id = @request_id\r\n AND s.recursion = 1\r\n OPTION (KEEPFIXED PLAN);\r\n END;\r\n ELSE\r\n BEGIN;\r\n UPDATE s\r\n SET\r\n s.query_plan =\r\n CASE ERROR_NUMBER()\r\n WHEN 1222 THEN '<timeout_exceeded />'\r\n ELSE '<error message=\"' + ERROR_MESSAGE() + '\" />'\r\n END\r\n FROM #sessions AS s\r\n WHERE\r\n s.session_id = @session_id\r\n AND s.request_id = @request_id\r\n AND s.recursion = 1\r\n OPTION (KEEPFIXED PLAN);\r\n END;\r\n END CATCH;\r\n END;\r\n\r\n FETCH NEXT FROM plan_cursor\r\n INTO\r\n @session_id,\r\n @request_id,\r\n @plan_handle,\r\n @statement_start_offset,\r\n @statement_end_offset;\r\n END;\r\n\r\n --Return this to the default\r\n SET LOCK_TIMEOUT -1;\r\n\r\n CLOSE plan_cursor;\r\n DEALLOCATE plan_cursor;\r\n END;\r\n\r\n IF\r\n @get_locks = 1\r\n AND @recursion = 1\r\n AND @output_column_list LIKE '%|[locks|]%' ESCAPE '|'\r\n BEGIN;\r\n DECLARE locks_cursor\r\n CURSOR LOCAL FAST_FORWARD\r\n FOR\r\n SELECT DISTINCT\r\n database_name\r\n FROM #locks\r\n WHERE\r\n EXISTS\r\n (\r\n SELECT *\r\n FROM #sessions AS s\r\n WHERE\r\n s.session_id = #locks.session_id\r\n AND recursion = 1\r\n )\r\n AND database_name <> '(null)'\r\n OPTION (KEEPFIXED PLAN);\r\n\r\n OPEN locks_cursor;\r\n\r\n FETCH NEXT FROM locks_cursor\r\n INTO\r\n @database_name;\r\n\r\n WHILE @@FETCH_STATUS = 0\r\n BEGIN;\r\n BEGIN TRY;\r\n SET @sql_n = CONVERT(NVARCHAR(MAX), N'') + N'\r\n UPDATE l\r\n SET\r\n object_name =\r\n REPLACE\r\n (\r\n REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\r\n REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\r\n REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\r\n o.name COLLATE Latin1_General_Bin2,\r\n NCHAR(31),N''?''),NCHAR(30),N''?''),NCHAR(29),N''?''),NCHAR(28),N''?''),NCHAR(27),N''?''),NCHAR(26),N''?''),NCHAR(25),N''?''),NCHAR(24),N''?''),NCHAR(23),N''?''),NCHAR(22),N''?''),\r\n NCHAR(21),N''?''),NCHAR(20),N''?''),NCHAR(19),N''?''),NCHAR(18),N''?''),NCHAR(17),N''?''),NCHAR(16),N''?''),NCHAR(15),N''?''),NCHAR(14),N''?''),NCHAR(12),N''?''),\r\n NCHAR(11),N''?''),NCHAR(8),N''?''),NCHAR(7),N''?''),NCHAR(6),N''?''),NCHAR(5),N''?''),NCHAR(4),N''?''),NCHAR(3),N''?''),NCHAR(2),N''?''),NCHAR(1),N''?''),\r\n NCHAR(0),\r\n N''''\r\n ),\r\n index_name =\r\n REPLACE\r\n (\r\n REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\r\n REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\r\n REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\r\n i.name COLLATE Latin1_General_Bin2,\r\n NCHAR(31),N''?''),NCHAR(30),N''?''),NCHAR(29),N''?''),NCHAR(28),N''?''),NCHAR(27),N''?''),NCHAR(26),N''?''),NCHAR(25),N''?''),NCHAR(24),N''?''),NCHAR(23),N''?''),NCHAR(22),N''?''),\r\n NCHAR(21),N''?''),NCHAR(20),N''?''),NCHAR(19),N''?''),NCHAR(18),N''?''),NCHAR(17),N''?''),NCHAR(16),N''?''),NCHAR(15),N''?''),NCHAR(14),N''?''),NCHAR(12),N''?''),\r\n NCHAR(11),N''?''),NCHAR(8),N''?''),NCHAR(7),N''?''),NCHAR(6),N''?''),NCHAR(5),N''?''),NCHAR(4),N''?''),NCHAR(3),N''?''),NCHAR(2),N''?''),NCHAR(1),N''?''),\r\n NCHAR(0),\r\n N''''\r\n ),\r\n schema_name =\r\n REPLACE\r\n (\r\n REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\r\n REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\r\n REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\r\n s.name COLLATE Latin1_General_Bin2,\r\n NCHAR(31),N''?''),NCHAR(30),N''?''),NCHAR(29),N''?''),NCHAR(28),N''?''),NCHAR(27),N''?''),NCHAR(26),N''?''),NCHAR(25),N''?''),NCHAR(24),N''?''),NCHAR(23),N''?''),NCHAR(22),N''?''),\r\n NCHAR(21),N''?''),NCHAR(20),N''?''),NCHAR(19),N''?''),NCHAR(18),N''?''),NCHAR(17),N''?''),NCHAR(16),N''?''),NCHAR(15),N''?''),NCHAR(14),N''?''),NCHAR(12),N''?''),\r\n NCHAR(11),N''?''),NCHAR(8),N''?''),NCHAR(7),N''?''),NCHAR(6),N''?''),NCHAR(5),N''?''),NCHAR(4),N''?''),NCHAR(3),N''?''),NCHAR(2),N''?''),NCHAR(1),N''?''),\r\n NCHAR(0),\r\n N''''\r\n ),\r\n principal_name =\r\n REPLACE\r\n (\r\n REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\r\n REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\r\n REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\r\n dp.name COLLATE Latin1_General_Bin2,\r\n NCHAR(31),N''?''),NCHAR(30),N''?''),NCHAR(29),N''?''),NCHAR(28),N''?''),NCHAR(27),N''?''),NCHAR(26),N''?''),NCHAR(25),N''?''),NCHAR(24),N''?''),NCHAR(23),N''?''),NCHAR(22),N''?''),\r\n NCHAR(21),N''?''),NCHAR(20),N''?''),NCHAR(19),N''?''),NCHAR(18),N''?''),NCHAR(17),N''?''),NCHAR(16),N''?''),NCHAR(15),N''?''),NCHAR(14),N''?''),NCHAR(12),N''?''),\r\n NCHAR(11),N''?''),NCHAR(8),N''?''),NCHAR(7),N''?''),NCHAR(6),N''?''),NCHAR(5),N''?''),NCHAR(4),N''?''),NCHAR(3),N''?''),NCHAR(2),N''?''),NCHAR(1),N''?''),\r\n NCHAR(0),\r\n N''''\r\n )\r\n FROM #locks AS l\r\n LEFT OUTER JOIN ' + QUOTENAME(@database_name) + N'.sys.allocation_units AS au ON\r\n au.allocation_unit_id = l.allocation_unit_id\r\n LEFT OUTER JOIN ' + QUOTENAME(@database_name) + N'.sys.partitions AS p ON\r\n p.hobt_id =\r\n COALESCE\r\n (\r\n l.hobt_id,\r\n CASE\r\n WHEN au.type IN (1, 3) THEN au.container_id\r\n ELSE NULL\r\n END\r\n )\r\n LEFT OUTER JOIN ' + QUOTENAME(@database_name) + N'.sys.partitions AS p1 ON\r\n l.hobt_id IS NULL\r\n AND au.type = 2\r\n AND p1.partition_id = au.container_id\r\n LEFT OUTER JOIN ' + QUOTENAME(@database_name) + N'.sys.objects AS o ON\r\n o.object_id = COALESCE(l.object_id, p.object_id, p1.object_id)\r\n LEFT OUTER JOIN ' + QUOTENAME(@database_name) + N'.sys.indexes AS i ON\r\n i.object_id = COALESCE(l.object_id, p.object_id, p1.object_id)\r\n AND i.index_id = COALESCE(l.index_id, p.index_id, p1.index_id)\r\n LEFT OUTER JOIN ' + QUOTENAME(@database_name) + N'.sys.schemas AS s ON\r\n s.schema_id = COALESCE(l.schema_id, o.schema_id)\r\n LEFT OUTER JOIN ' + QUOTENAME(@database_name) + N'.sys.database_principals AS dp ON\r\n dp.principal_id = l.principal_id\r\n WHERE\r\n l.database_name = @database_name\r\n OPTION (KEEPFIXED PLAN); ';\r\n\r\n EXEC sp_executesql\r\n @sql_n,\r\n N'@database_name sysname',\r\n @database_name;\r\n END TRY\r\n BEGIN CATCH;\r\n UPDATE #locks\r\n SET\r\n query_error =\r\n REPLACE\r\n (\r\n REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\r\n REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\r\n REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\r\n CONVERT\r\n (\r\n NVARCHAR(MAX),\r\n ERROR_MESSAGE() COLLATE Latin1_General_Bin2\r\n ),\r\n NCHAR(31),N'?'),NCHAR(30),N'?'),NCHAR(29),N'?'),NCHAR(28),N'?'),NCHAR(27),N'?'),NCHAR(26),N'?'),NCHAR(25),N'?'),NCHAR(24),N'?'),NCHAR(23),N'?'),NCHAR(22),N'?'),\r\n NCHAR(21),N'?'),NCHAR(20),N'?'),NCHAR(19),N'?'),NCHAR(18),N'?'),NCHAR(17),N'?'),NCHAR(16),N'?'),NCHAR(15),N'?'),NCHAR(14),N'?'),NCHAR(12),N'?'),\r\n NCHAR(11),N'?'),NCHAR(8),N'?'),NCHAR(7),N'?'),NCHAR(6),N'?'),NCHAR(5),N'?'),NCHAR(4),N'?'),NCHAR(3),N'?'),NCHAR(2),N'?'),NCHAR(1),N'?'),\r\n NCHAR(0),\r\n N''\r\n )\r\n WHERE\r\n database_name = @database_name\r\n OPTION (KEEPFIXED PLAN);\r\n END CATCH;\r\n\r\n FETCH NEXT FROM locks_cursor\r\n INTO\r\n @database_name;\r\n END;\r\n\r\n CLOSE locks_cursor;\r\n DEALLOCATE locks_cursor;\r\n\r\n CREATE CLUSTERED INDEX IX_SRD ON #locks (session_id, request_id, database_name);\r\n\r\n UPDATE s\r\n SET\r\n s.locks =\r\n (\r\n SELECT\r\n REPLACE\r\n (\r\n REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\r\n REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\r\n REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\r\n CONVERT\r\n (\r\n NVARCHAR(MAX),\r\n l1.database_name COLLATE Latin1_General_Bin2\r\n ),\r\n NCHAR(31),N'?'),NCHAR(30),N'?'),NCHAR(29),N'?'),NCHAR(28),N'?'),NCHAR(27),N'?'),NCHAR(26),N'?'),NCHAR(25),N'?'),NCHAR(24),N'?'),NCHAR(23),N'?'),NCHAR(22),N'?'),\r\n NCHAR(21),N'?'),NCHAR(20),N'?'),NCHAR(19),N'?'),NCHAR(18),N'?'),NCHAR(17),N'?'),NCHAR(16),N'?'),NCHAR(15),N'?'),NCHAR(14),N'?'),NCHAR(12),N'?'),\r\n NCHAR(11),N'?'),NCHAR(8),N'?'),NCHAR(7),N'?'),NCHAR(6),N'?'),NCHAR(5),N'?'),NCHAR(4),N'?'),NCHAR(3),N'?'),NCHAR(2),N'?'),NCHAR(1),N'?'),\r\n NCHAR(0),\r\n N''\r\n ) AS [Database/@name],\r\n MIN(l1.query_error) AS [Database/@query_error],\r\n (\r\n SELECT\r\n l2.request_mode AS [Lock/@request_mode],\r\n l2.request_status AS [Lock/@request_status],\r\n COUNT(*) AS [Lock/@request_count]\r\n FROM #locks AS l2\r\n WHERE\r\n l1.session_id = l2.session_id\r\n AND l1.request_id = l2.request_id\r\n AND l2.database_name = l1.database_name\r\n AND l2.resource_type = 'DATABASE'\r\n GROUP BY\r\n l2.request_mode,\r\n l2.request_status\r\n FOR XML\r\n PATH(''),\r\n TYPE\r\n ) AS [Database/Locks],\r\n (\r\n SELECT\r\n COALESCE(l3.object_name, '(null)') AS [Object/@name],\r\n l3.schema_name AS [Object/@schema_name],\r\n (\r\n SELECT\r\n l4.resource_type AS [Lock/@resource_type],\r\n l4.page_type AS [Lock/@page_type],\r\n l4.index_name AS [Lock/@index_name],\r\n CASE\r\n WHEN l4.object_name IS NULL THEN l4.schema_name\r\n ELSE NULL\r\n END AS [Lock/@schema_name],\r\n l4.principal_name AS [Lock/@principal_name],\r\n REPLACE\r\n (\r\n REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\r\n REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\r\n REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\r\n l4.resource_description COLLATE Latin1_General_Bin2,\r\n NCHAR(31),N'?'),NCHAR(30),N'?'),NCHAR(29),N'?'),NCHAR(28),N'?'),NCHAR(27),N'?'),NCHAR(26),N'?'),NCHAR(25),N'?'),NCHAR(24),N'?'),NCHAR(23),N'?'),NCHAR(22),N'?'),\r\n NCHAR(21),N'?'),NCHAR(20),N'?'),NCHAR(19),N'?'),NCHAR(18),N'?'),NCHAR(17),N'?'),NCHAR(16),N'?'),NCHAR(15),N'?'),NCHAR(14),N'?'),NCHAR(12),N'?'),\r\n NCHAR(11),N'?'),NCHAR(8),N'?'),NCHAR(7),N'?'),NCHAR(6),N'?'),NCHAR(5),N'?'),NCHAR(4),N'?'),NCHAR(3),N'?'),NCHAR(2),N'?'),NCHAR(1),N'?'),\r\n NCHAR(0),\r\n N''\r\n ) AS [Lock/@resource_description],\r\n l4.request_mode AS [Lock/@request_mode],\r\n l4.request_status AS [Lock/@request_status],\r\n SUM(l4.request_count) AS [Lock/@request_count]\r\n FROM #locks AS l4\r\n WHERE\r\n l4.session_id = l3.session_id\r\n AND l4.request_id = l3.request_id\r\n AND l3.database_name = l4.database_name\r\n AND COALESCE(l3.object_name, '(null)') = COALESCE(l4.object_name, '(null)')\r\n AND COALESCE(l3.schema_name, '') = COALESCE(l4.schema_name, '')\r\n AND l4.resource_type <> 'DATABASE'\r\n GROUP BY\r\n l4.resource_type,\r\n l4.page_type,\r\n l4.index_name,\r\n CASE\r\n WHEN l4.object_name IS NULL THEN l4.schema_name\r\n ELSE NULL\r\n END,\r\n l4.principal_name,\r\n l4.resource_description,\r\n l4.request_mode,\r\n l4.request_status\r\n FOR XML\r\n PATH(''),\r\n TYPE\r\n ) AS [Object/Locks]\r\n FROM #locks AS l3\r\n WHERE\r\n l3.session_id = l1.session_id\r\n AND l3.request_id = l1.request_id\r\n AND l3.database_name = l1.database_name\r\n AND l3.resource_type <> 'DATABASE'\r\n GROUP BY\r\n l3.session_id,\r\n l3.request_id,\r\n l3.database_name,\r\n COALESCE(l3.object_name, '(null)'),\r\n l3.schema_name\r\n FOR XML\r\n PATH(''),\r\n TYPE\r\n ) AS [Database/Objects]\r\n FROM #locks AS l1\r\n WHERE\r\n l1.session_id = s.session_id\r\n AND l1.request_id = s.request_id\r\n AND l1.start_time IN (s.start_time, s.last_request_start_time)\r\n AND s.recursion = 1\r\n GROUP BY\r\n l1.session_id,\r\n l1.request_id,\r\n l1.database_name\r\n FOR XML\r\n PATH(''),\r\n TYPE\r\n )\r\n FROM #sessions s\r\n OPTION (KEEPFIXED PLAN);\r\n END;\r\n\r\n IF\r\n @find_block_leaders = 1\r\n AND @recursion = 1\r\n AND @output_column_list LIKE '%|[blocked_session_count|]%' ESCAPE '|'\r\n BEGIN;\r\n WITH\r\n blockers AS\r\n (\r\n SELECT\r\n session_id,\r\n session_id AS top_level_session_id,\r\n CONVERT(VARCHAR(8000), '.' + CONVERT(VARCHAR(8000), session_id) + '.') AS the_path\r\n FROM #sessions\r\n WHERE\r\n recursion = 1\r\n\r\n UNION ALL\r\n\r\n SELECT\r\n s.session_id,\r\n b.top_level_session_id,\r\n CONVERT(VARCHAR(8000), b.the_path + CONVERT(VARCHAR(8000), s.session_id) + '.') AS the_path\r\n FROM blockers AS b\r\n JOIN #sessions AS s ON\r\n s.blocking_session_id = b.session_id\r\n AND s.recursion = 1\r\n AND b.the_path NOT LIKE '%.' + CONVERT(VARCHAR(8000), s.session_id) + '.%' COLLATE Latin1_General_Bin2\r\n )\r\n UPDATE s\r\n SET\r\n s.blocked_session_count = x.blocked_session_count\r\n FROM #sessions AS s\r\n JOIN\r\n (\r\n SELECT\r\n b.top_level_session_id AS session_id,\r\n COUNT(*) - 1 AS blocked_session_count\r\n FROM blockers AS b\r\n GROUP BY\r\n b.top_level_session_id\r\n ) x ON\r\n s.session_id = x.session_id\r\n WHERE\r\n s.recursion = 1;\r\n END;\r\n\r\n IF\r\n @get_task_info = 2\r\n AND @output_column_list LIKE '%|[additional_info|]%' ESCAPE '|'\r\n AND @recursion = 1\r\n BEGIN;\r\n CREATE TABLE #blocked_requests\r\n (\r\n session_id SMALLINT NOT NULL,\r\n request_id INT NOT NULL,\r\n database_name sysname NOT NULL,\r\n object_id INT,\r\n hobt_id BIGINT,\r\n schema_id INT,\r\n schema_name sysname NULL,\r\n object_name sysname NULL,\r\n query_error NVARCHAR(2048),\r\n PRIMARY KEY (database_name, session_id, request_id)\r\n );\r\n\r\n CREATE STATISTICS s_database_name ON #blocked_requests (database_name)\r\n WITH SAMPLE 0 ROWS, NORECOMPUTE;\r\n CREATE STATISTICS s_schema_name ON #blocked_requests (schema_name)\r\n WITH SAMPLE 0 ROWS, NORECOMPUTE;\r\n CREATE STATISTICS s_object_name ON #blocked_requests (object_name)\r\n WITH SAMPLE 0 ROWS, NORECOMPUTE;\r\n CREATE STATISTICS s_query_error ON #blocked_requests (query_error)\r\n WITH SAMPLE 0 ROWS, NORECOMPUTE;\r\n \r\n INSERT #blocked_requests\r\n (\r\n session_id,\r\n request_id,\r\n database_name,\r\n object_id,\r\n hobt_id,\r\n schema_id\r\n )\r\n SELECT\r\n session_id,\r\n request_id,\r\n database_name,\r\n object_id,\r\n hobt_id,\r\n CONVERT(INT, SUBSTRING(schema_node, CHARINDEX(' = ', schema_node) + 3, LEN(schema_node))) AS schema_id\r\n FROM\r\n (\r\n SELECT\r\n session_id,\r\n request_id,\r\n agent_nodes.agent_node.value('(database_name/text())[1]', 'sysname') AS database_name,\r\n agent_nodes.agent_node.value('(object_id/text())[1]', 'int') AS object_id,\r\n agent_nodes.agent_node.value('(hobt_id/text())[1]', 'bigint') AS hobt_id,\r\n agent_nodes.agent_node.value('(metadata_resource/text()[.=\"SCHEMA\"]/../../metadata_class_id/text())[1]', 'varchar(100)') AS schema_node\r\n FROM #sessions AS s\r\n CROSS APPLY s.additional_info.nodes('//block_info') AS agent_nodes (agent_node)\r\n WHERE\r\n s.recursion = 1\r\n ) AS t\r\n WHERE\r\n t.database_name IS NOT NULL\r\n AND\r\n (\r\n t.object_id IS NOT NULL\r\n OR t.hobt_id IS NOT NULL\r\n OR t.schema_node IS NOT NULL\r\n );\r\n \r\n DECLARE blocks_cursor\r\n CURSOR LOCAL FAST_FORWARD\r\n FOR\r\n SELECT DISTINCT\r\n database_name\r\n FROM #blocked_requests;\r\n \r\n OPEN blocks_cursor;\r\n \r\n FETCH NEXT FROM blocks_cursor\r\n INTO\r\n @database_name;\r\n \r\n WHILE @@FETCH_STATUS = 0\r\n BEGIN;\r\n BEGIN TRY;\r\n SET @sql_n =\r\n CONVERT(NVARCHAR(MAX), N'') + N'\r\n UPDATE b\r\n SET\r\n b.schema_name =\r\n REPLACE\r\n (\r\n REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\r\n REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\r\n REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\r\n s.name COLLATE Latin1_General_Bin2,\r\n NCHAR(31),N''?''),NCHAR(30),N''?''),NCHAR(29),N''?''),NCHAR(28),N''?''),NCHAR(27),N''?''),NCHAR(26),N''?''),NCHAR(25),N''?''),NCHAR(24),N''?''),NCHAR(23),N''?''),NCHAR(22),N''?''),\r\n NCHAR(21),N''?''),NCHAR(20),N''?''),NCHAR(19),N''?''),NCHAR(18),N''?''),NCHAR(17),N''?''),NCHAR(16),N''?''),NCHAR(15),N''?''),NCHAR(14),N''?''),NCHAR(12),N''?''),\r\n NCHAR(11),N''?''),NCHAR(8),N''?''),NCHAR(7),N''?''),NCHAR(6),N''?''),NCHAR(5),N''?''),NCHAR(4),N''?''),NCHAR(3),N''?''),NCHAR(2),N''?''),NCHAR(1),N''?''),\r\n NCHAR(0),\r\n N''''\r\n ),\r\n b.object_name =\r\n REPLACE\r\n (\r\n REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\r\n REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\r\n REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\r\n o.name COLLATE Latin1_General_Bin2,\r\n NCHAR(31),N''?''),NCHAR(30),N''?''),NCHAR(29),N''?''),NCHAR(28),N''?''),NCHAR(27),N''?''),NCHAR(26),N''?''),NCHAR(25),N''?''),NCHAR(24),N''?''),NCHAR(23),N''?''),NCHAR(22),N''?''),\r\n NCHAR(21),N''?''),NCHAR(20),N''?''),NCHAR(19),N''?''),NCHAR(18),N''?''),NCHAR(17),N''?''),NCHAR(16),N''?''),NCHAR(15),N''?''),NCHAR(14),N''?''),NCHAR(12),N''?''),\r\n NCHAR(11),N''?''),NCHAR(8),N''?''),NCHAR(7),N''?''),NCHAR(6),N''?''),NCHAR(5),N''?''),NCHAR(4),N''?''),NCHAR(3),N''?''),NCHAR(2),N''?''),NCHAR(1),N''?''),\r\n NCHAR(0),\r\n N''''\r\n )\r\n FROM #blocked_requests AS b\r\n LEFT OUTER JOIN ' + QUOTENAME(@database_name) + N'.sys.partitions AS p ON\r\n p.hobt_id = b.hobt_id\r\n LEFT OUTER JOIN ' + QUOTENAME(@database_name) + N'.sys.objects AS o ON\r\n o.object_id = COALESCE(p.object_id, b.object_id)\r\n LEFT OUTER JOIN ' + QUOTENAME(@database_name) + N'.sys.schemas AS s ON\r\n s.schema_id = COALESCE(o.schema_id, b.schema_id)\r\n WHERE\r\n b.database_name = @database_name; ';\r\n \r\n EXEC sp_executesql\r\n @sql_n,\r\n N'@database_name sysname',\r\n @database_name;\r\n END TRY\r\n BEGIN CATCH;\r\n UPDATE #blocked_requests\r\n SET\r\n query_error =\r\n REPLACE\r\n (\r\n REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\r\n REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\r\n REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\r\n CONVERT\r\n (\r\n NVARCHAR(MAX),\r\n ERROR_MESSAGE() COLLATE Latin1_General_Bin2\r\n ),\r\n NCHAR(31),N'?'),NCHAR(30),N'?'),NCHAR(29),N'?'),NCHAR(28),N'?'),NCHAR(27),N'?'),NCHAR(26),N'?'),NCHAR(25),N'?'),NCHAR(24),N'?'),NCHAR(23),N'?'),NCHAR(22),N'?'),\r\n NCHAR(21),N'?'),NCHAR(20),N'?'),NCHAR(19),N'?'),NCHAR(18),N'?'),NCHAR(17),N'?'),NCHAR(16),N'?'),NCHAR(15),N'?'),NCHAR(14),N'?'),NCHAR(12),N'?'),\r\n NCHAR(11),N'?'),NCHAR(8),N'?'),NCHAR(7),N'?'),NCHAR(6),N'?'),NCHAR(5),N'?'),NCHAR(4),N'?'),NCHAR(3),N'?'),NCHAR(2),N'?'),NCHAR(1),N'?'),\r\n NCHAR(0),\r\n N''\r\n )\r\n WHERE\r\n database_name = @database_name;\r\n END CATCH;\r\n\r\n FETCH NEXT FROM blocks_cursor\r\n INTO\r\n @database_name;\r\n END;\r\n \r\n CLOSE blocks_cursor;\r\n DEALLOCATE blocks_cursor;\r\n \r\n UPDATE s\r\n SET\r\n additional_info.modify\r\n ('\r\n insert <schema_name>{sql:column(\"b.schema_name\")}</schema_name>\r\n as last\r\n into (/additional_info/block_info)[1]\r\n ')\r\n FROM #sessions AS s\r\n INNER JOIN #blocked_requests AS b ON\r\n b.session_id = s.session_id\r\n AND b.request_id = s.request_id\r\n AND s.recursion = 1\r\n WHERE\r\n b.schema_name IS NOT NULL;\r\n\r\n UPDATE s\r\n SET\r\n additional_info.modify\r\n ('\r\n insert <object_name>{sql:column(\"b.object_name\")}</object_name>\r\n as last\r\n into (/additional_info/block_info)[1]\r\n ')\r\n FROM #sessions AS s\r\n INNER JOIN #blocked_requests AS b ON\r\n b.session_id = s.session_id\r\n AND b.request_id = s.request_id\r\n AND s.recursion = 1\r\n WHERE\r\n b.object_name IS NOT NULL;\r\n\r\n UPDATE s\r\n SET\r\n additional_info.modify\r\n ('\r\n insert <query_error>{sql:column(\"b.query_error\")}</query_error>\r\n as last\r\n into (/additional_info/block_info)[1]\r\n ')\r\n FROM #sessions AS s\r\n INNER JOIN #blocked_requests AS b ON\r\n b.session_id = s.session_id\r\n AND b.request_id = s.request_id\r\n AND s.recursion = 1\r\n WHERE\r\n b.query_error IS NOT NULL;\r\n END;\r\n\r\n IF\r\n @output_column_list LIKE '%|[program_name|]%' ESCAPE '|'\r\n AND @output_column_list LIKE '%|[additional_info|]%' ESCAPE '|'\r\n AND @recursion = 1\r\n AND DB_ID('msdb') IS NOT NULL\r\n BEGIN;\r\n SET @sql_n =\r\n N'BEGIN TRY;\r\n DECLARE @job_name sysname;\r\n SET @job_name = NULL;\r\n DECLARE @step_name sysname;\r\n SET @step_name = NULL;\r\n\r\n SELECT\r\n @job_name =\r\n REPLACE\r\n (\r\n REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\r\n REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\r\n REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\r\n j.name,\r\n NCHAR(31),N''?''),NCHAR(30),N''?''),NCHAR(29),N''?''),NCHAR(28),N''?''),NCHAR(27),N''?''),NCHAR(26),N''?''),NCHAR(25),N''?''),NCHAR(24),N''?''),NCHAR(23),N''?''),NCHAR(22),N''?''),\r\n NCHAR(21),N''?''),NCHAR(20),N''?''),NCHAR(19),N''?''),NCHAR(18),N''?''),NCHAR(17),N''?''),NCHAR(16),N''?''),NCHAR(15),N''?''),NCHAR(14),N''?''),NCHAR(12),N''?''),\r\n NCHAR(11),N''?''),NCHAR(8),N''?''),NCHAR(7),N''?''),NCHAR(6),N''?''),NCHAR(5),N''?''),NCHAR(4),N''?''),NCHAR(3),N''?''),NCHAR(2),N''?''),NCHAR(1),N''?''),\r\n NCHAR(0),\r\n N''?''\r\n ),\r\n @step_name =\r\n REPLACE\r\n (\r\n REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\r\n REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\r\n REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\r\n s.step_name,\r\n NCHAR(31),N''?''),NCHAR(30),N''?''),NCHAR(29),N''?''),NCHAR(28),N''?''),NCHAR(27),N''?''),NCHAR(26),N''?''),NCHAR(25),N''?''),NCHAR(24),N''?''),NCHAR(23),N''?''),NCHAR(22),N''?''),\r\n NCHAR(21),N''?''),NCHAR(20),N''?''),NCHAR(19),N''?''),NCHAR(18),N''?''),NCHAR(17),N''?''),NCHAR(16),N''?''),NCHAR(15),N''?''),NCHAR(14),N''?''),NCHAR(12),N''?''),\r\n NCHAR(11),N''?''),NCHAR(8),N''?''),NCHAR(7),N''?''),NCHAR(6),N''?''),NCHAR(5),N''?''),NCHAR(4),N''?''),NCHAR(3),N''?''),NCHAR(2),N''?''),NCHAR(1),N''?''),\r\n NCHAR(0),\r\n N''?''\r\n )\r\n FROM msdb.dbo.sysjobs AS j\r\n INNER JOIN msdb.dbo.sysjobsteps AS s ON\r\n j.job_id = s.job_id\r\n WHERE\r\n j.job_id = @job_id\r\n AND s.step_id = @step_id;\r\n\r\n IF @job_name IS NOT NULL\r\n BEGIN;\r\n UPDATE s\r\n SET\r\n additional_info.modify\r\n (''\r\n insert text{sql:variable(\"@job_name\")}\r\n into (/additional_info/agent_job_info/job_name)[1]\r\n '')\r\n FROM #sessions AS s\r\n WHERE\r\n s.session_id = @session_id\r\n AND s.recursion = 1\r\n OPTION (KEEPFIXED PLAN);\r\n \r\n UPDATE s\r\n SET\r\n additional_info.modify\r\n (''\r\n insert text{sql:variable(\"@step_name\")}\r\n into (/additional_info/agent_job_info/step_name)[1]\r\n '')\r\n FROM #sessions AS s\r\n WHERE\r\n s.session_id = @session_id\r\n AND s.recursion = 1\r\n OPTION (KEEPFIXED PLAN);\r\n END;\r\n END TRY\r\n BEGIN CATCH;\r\n DECLARE @msdb_error_message NVARCHAR(256);\r\n SET @msdb_error_message = ERROR_MESSAGE();\r\n \r\n UPDATE s\r\n SET\r\n additional_info.modify\r\n (''\r\n insert <msdb_query_error>{sql:variable(\"@msdb_error_message\")}</msdb_query_error>\r\n as last\r\n into (/additional_info/agent_job_info)[1]\r\n '')\r\n FROM #sessions AS s\r\n WHERE\r\n s.session_id = @session_id\r\n AND s.recursion = 1\r\n OPTION (KEEPFIXED PLAN);\r\n END CATCH;'\r\n\r\n DECLARE @job_id UNIQUEIDENTIFIER;\r\n DECLARE @step_id INT;\r\n\r\n DECLARE agent_cursor\r\n CURSOR LOCAL FAST_FORWARD\r\n FOR\r\n SELECT\r\n s.session_id,\r\n agent_nodes.agent_node.value('(job_id/text())[1]', 'uniqueidentifier') AS job_id,\r\n agent_nodes.agent_node.value('(step_id/text())[1]', 'int') AS step_id\r\n FROM #sessions AS s\r\n CROSS APPLY s.additional_info.nodes('//agent_job_info') AS agent_nodes (agent_node)\r\n WHERE\r\n s.recursion = 1\r\n OPTION (KEEPFIXED PLAN);\r\n \r\n OPEN agent_cursor;\r\n\r\n FETCH NEXT FROM agent_cursor\r\n INTO\r\n @session_id,\r\n @job_id,\r\n @step_id;\r\n\r\n WHILE @@FETCH_STATUS = 0\r\n BEGIN;\r\n EXEC sp_executesql\r\n @sql_n,\r\n N'@job_id UNIQUEIDENTIFIER, @step_id INT, @session_id SMALLINT',\r\n @job_id, @step_id, @session_id\r\n\r\n FETCH NEXT FROM agent_cursor\r\n INTO\r\n @session_id,\r\n @job_id,\r\n @step_id;\r\n END;\r\n\r\n CLOSE agent_cursor;\r\n DEALLOCATE agent_cursor;\r\n END;\r\n \r\n IF\r\n @delta_interval > 0\r\n AND @recursion <> 1\r\n BEGIN;\r\n SET @recursion = 1;\r\n\r\n DECLARE @delay_time CHAR(12);\r\n SET @delay_time = CONVERT(VARCHAR, DATEADD(second, @delta_interval, 0), 114);\r\n WAITFOR DELAY @delay_time;\r\n\r\n GOTO REDO;\r\n END;\r\n END;\r\n\r\n DECLARE\r\n @num_data_threshold MONEY,\r\n @num_col_fmt NVARCHAR(MAX),\r\n @num_delta_col_fmt NVARCHAR(MAX);\r\n\r\n SET @num_data_threshold = 919919919919919;\r\n SET @num_col_fmt =\r\n CASE @format_output\r\n WHEN 1 THEN N'\r\n CONVERT(VARCHAR, SPACE(MAX(LEN(CONVERT(VARCHAR, [col_name]))) OVER() - LEN(CONVERT(VARCHAR, [col_name]))) + LEFT(CONVERT(CHAR(22), CONVERT(MONEY, CASE WHEN [col_name] > @num_data_threshold THEN @num_data_threshold ELSE [col_name] END), 1), 19)) AS '\r\n WHEN 2 THEN N'\r\n CONVERT(VARCHAR, LEFT(CONVERT(CHAR(22), CONVERT(MONEY, CASE WHEN [col_name] > @num_data_threshold THEN @num_data_threshold ELSE [col_name] END), 1), 19)) AS '\r\n ELSE N''\r\n END + N'[col_name], ';\r\n SET @num_delta_col_fmt =\r\n N'\r\n CASE\r\n WHEN\r\n first_request_start_time = last_request_start_time\r\n AND num_events = 2\r\n AND [col_name] >= 0\r\n THEN ' +\r\n CASE @format_output\r\n WHEN 1 THEN N'CONVERT(VARCHAR, SPACE(MAX(LEN(CONVERT(VARCHAR, [col_name]))) OVER() - LEN(CONVERT(VARCHAR, [col_name]))) + LEFT(CONVERT(CHAR(22), CONVERT(MONEY, CASE WHEN [col_name] > @num_data_threshold THEN @num_data_threshold ELSE [col_name] END), 1), 19)) '\r\n WHEN 2 THEN N'CONVERT(VARCHAR, LEFT(CONVERT(CHAR(22), CONVERT(MONEY, CASE WHEN [col_name] > @num_data_threshold THEN @num_data_threshold ELSE [col_name] END), 1), 19)) '\r\n ELSE N'[col_name] '\r\n END + N'\r\n ELSE NULL\r\n END AS [col_name], ';\r\n\r\n SET @sql_n = CONVERT(NVARCHAR(MAX), N'') +\r\n --Outer column list\r\n CASE\r\n WHEN\r\n @destination_table <> ''\r\n AND @return_schema = 0\r\n THEN N'INSERT ' + @destination_table + ' '\r\n ELSE N''\r\n END +\r\n N'SELECT ' +\r\n @output_column_list + N' ' +\r\n CASE @return_schema\r\n WHEN 1 THEN N'INTO #session_schema '\r\n ELSE N''\r\n END\r\n --End outer column list\r\n +\r\n --Inner column list\r\n N'\r\n FROM\r\n (\r\n SELECT\r\n session_id, ' +\r\n --[dd hh:mm:ss.mss]\r\n CASE\r\n WHEN @format_output IN (1, 2) THEN\r\n N'\r\n CASE\r\n WHEN elapsed_time < 0 THEN\r\n RIGHT\r\n (\r\n REPLICATE(''0'', max_elapsed_length) + CONVERT(VARCHAR, (-1 * elapsed_time) / 86400),\r\n max_elapsed_length\r\n ) +\r\n RIGHT\r\n (\r\n CONVERT(VARCHAR, DATEADD(second, (-1 * elapsed_time), 0), 120),\r\n 9\r\n ) +\r\n ''.000''\r\n ELSE\r\n RIGHT\r\n (\r\n REPLICATE(''0'', max_elapsed_length) + CONVERT(VARCHAR, elapsed_time / 86400000),\r\n max_elapsed_length\r\n ) +\r\n RIGHT\r\n (\r\n CONVERT(VARCHAR, DATEADD(second, elapsed_time / 1000, 0), 120),\r\n 9\r\n ) +\r\n ''.'' +\r\n RIGHT(''000'' + CONVERT(VARCHAR, elapsed_time % 1000), 3)\r\n END AS [dd hh:mm:ss.mss], '\r\n ELSE\r\n N''\r\n END +\r\n --[dd hh:mm:ss.mss (avg)] / avg_elapsed_time\r\n CASE\r\n WHEN @format_output IN (1, 2) THEN\r\n N'\r\n RIGHT\r\n (\r\n ''00'' + CONVERT(VARCHAR, avg_elapsed_time / 86400000),\r\n 2\r\n ) +\r\n RIGHT\r\n (\r\n CONVERT(VARCHAR, DATEADD(second, avg_elapsed_time / 1000, 0), 120),\r\n 9\r\n ) +\r\n ''.'' +\r\n RIGHT(''000'' + CONVERT(VARCHAR, avg_elapsed_time % 1000), 3) AS [dd hh:mm:ss.mss (avg)], '\r\n ELSE\r\n N'avg_elapsed_time, '\r\n END +\r\n REPLACE(@num_col_fmt, N'[col_name]', N'physical_io') +\r\n REPLACE(@num_col_fmt, N'[col_name]', N'reads') +\r\n REPLACE(@num_col_fmt, N'[col_name]', N'physical_reads') +\r\n REPLACE(@num_col_fmt, N'[col_name]', N'writes') +\r\n REPLACE(@num_col_fmt, N'[col_name]', N'tempdb_allocations') +\r\n REPLACE(@num_col_fmt, N'[col_name]', N'tempdb_current') +\r\n REPLACE(@num_col_fmt, N'[col_name]', N'CPU') +\r\n REPLACE(@num_col_fmt, N'[col_name]', N'context_switches') +\r\n REPLACE(@num_col_fmt, N'[col_name]', N'used_memory') +\r\n REPLACE(@num_col_fmt, N'[col_name]', N'max_used_memory') +\r\n REPLACE(@num_col_fmt, N'[col_name]', N'requested_memory') +\r\n REPLACE(@num_col_fmt, N'[col_name]', N'granted_memory') +\r\n CASE\r\n WHEN @output_column_list LIKE '%|_delta|]%' ESCAPE '|' THEN\r\n REPLACE(@num_delta_col_fmt, N'[col_name]', N'physical_io_delta') +\r\n REPLACE(@num_delta_col_fmt, N'[col_name]', N'reads_delta') +\r\n REPLACE(@num_delta_col_fmt, N'[col_name]', N'physical_reads_delta') +\r\n REPLACE(@num_delta_col_fmt, N'[col_name]', N'writes_delta') +\r\n REPLACE(@num_delta_col_fmt, N'[col_name]', N'tempdb_allocations_delta') +\r\n --this is the only one that can (legitimately) go negative\r\n REPLACE(@num_delta_col_fmt, N'[col_name]', N'tempdb_current_delta') +\r\n --CPU_delta\r\n --leaving this one hardcoded, as there is a bit of different interaction here\r\n N'\r\n CASE\r\n WHEN\r\n first_request_start_time = last_request_start_time\r\n AND num_events = 2\r\n THEN\r\n CASE\r\n WHEN\r\n thread_CPU_delta > CPU_delta\r\n AND thread_CPU_delta > 0\r\n THEN ' +\r\n CASE @format_output\r\n WHEN 1 THEN N'CONVERT(VARCHAR, SPACE(MAX(LEN(CONVERT(VARCHAR, thread_CPU_delta + CPU_delta))) OVER() - LEN(CONVERT(VARCHAR, thread_CPU_delta))) + LEFT(CONVERT(CHAR(22), CONVERT(MONEY, CASE WHEN thread_CPU_delta > @num_data_threshold THEN @num_data_threshold ELSE thread_CPU_delta END), 1), 19)) '\r\n WHEN 2 THEN N'CONVERT(VARCHAR, LEFT(CONVERT(CHAR(22), CONVERT(MONEY, CASE WHEN thread_CPU_delta > @num_data_threshold THEN @num_data_threshold ELSE thread_CPU_delta END), 1), 19)) '\r\n ELSE N'thread_CPU_delta '\r\n END + N'\r\n WHEN CPU_delta >= 0 THEN ' +\r\n CASE @format_output\r\n WHEN 1 THEN N'CONVERT(VARCHAR, SPACE(MAX(LEN(CONVERT(VARCHAR, thread_CPU_delta + CPU_delta))) OVER() - LEN(CONVERT(VARCHAR, CPU_delta))) + LEFT(CONVERT(CHAR(22), CONVERT(MONEY, CASE WHEN CPU_delta > @num_data_threshold THEN @num_data_threshold ELSE CPU_delta END), 1), 19)) '\r\n WHEN 2 THEN N'CONVERT(VARCHAR, LEFT(CONVERT(CHAR(22), CONVERT(MONEY, CASE WHEN CPU_delta > @num_data_threshold THEN @num_data_threshold ELSE CPU_delta END), 1), 19)) '\r\n ELSE N'CPU_delta '\r\n END + N'\r\n ELSE NULL\r\n END\r\n ELSE\r\n NULL\r\n END AS CPU_delta, ' +\r\n REPLACE(@num_delta_col_fmt, N'[col_name]', N'context_switches_delta') +\r\n REPLACE(@num_delta_col_fmt, N'[col_name]', N'used_memory_delta') +\r\n REPLACE(@num_delta_col_fmt, N'[col_name]', N'max_used_memory_delta')\r\n ELSE N''\r\n END + N'\r\n ' +\r\n REPLACE(@num_col_fmt, N'[col_name]', N'tasks') + N'\r\n status,\r\n wait_info,\r\n locks,\r\n tran_start_time,\r\n LEFT(tran_log_writes, LEN(tran_log_writes) - 1) AS tran_log_writes,\r\n implicit_tran, ' +\r\n REPLACE(@num_col_fmt, '[col_name]', 'open_tran_count') + N'\r\n ' +\r\n --sql_command\r\n CASE @format_output\r\n WHEN 0 THEN N'REPLACE(REPLACE(CONVERT(NVARCHAR(MAX), sql_command), ''<?query --''+CHAR(13)+CHAR(10), ''''), CHAR(13)+CHAR(10)+''--?>'', '''') AS '\r\n ELSE N''\r\n END + N'sql_command,\r\n ' +\r\n --sql_text\r\n CASE @format_output\r\n WHEN 0 THEN N'REPLACE(REPLACE(CONVERT(NVARCHAR(MAX), sql_text), ''<?query --''+CHAR(13)+CHAR(10), ''''), CHAR(13)+CHAR(10)+''--?>'', '''') AS '\r\n ELSE N''\r\n END + N'sql_text,\r\n query_plan,\r\n blocking_session_id, ' +\r\n REPLACE(@num_col_fmt, N'[col_name]', N'blocked_session_count') +\r\n REPLACE(@num_col_fmt, N'[col_name]', N'percent_complete') + N'\r\n host_name,\r\n login_name,\r\n database_name,\r\n program_name,\r\n additional_info,\r\n memory_info,\r\n start_time,\r\n login_time,\r\n CASE\r\n WHEN status = N''sleeping'' THEN NULL\r\n ELSE request_id\r\n END AS request_id,\r\n GETDATE() AS collection_time '\r\n --End inner column list\r\n +\r\n --Derived table and INSERT specification\r\n N'\r\n FROM\r\n (\r\n SELECT TOP(2147483647)\r\n *,\r\n CASE\r\n MAX\r\n (\r\n LEN\r\n (\r\n CONVERT\r\n (\r\n VARCHAR,\r\n CASE\r\n WHEN elapsed_time < 0 THEN\r\n (-1 * elapsed_time) / 86400\r\n ELSE\r\n elapsed_time / 86400000\r\n END\r\n )\r\n )\r\n ) OVER ()\r\n WHEN 1 THEN 2\r\n ELSE\r\n MAX\r\n (\r\n LEN\r\n (\r\n CONVERT\r\n (\r\n VARCHAR,\r\n CASE\r\n WHEN elapsed_time < 0 THEN\r\n (-1 * elapsed_time) / 86400\r\n ELSE\r\n elapsed_time / 86400000\r\n END\r\n )\r\n )\r\n ) OVER ()\r\n END AS max_elapsed_length, ' +\r\n CASE\r\n WHEN @output_column_list LIKE '%|_delta|]%' ESCAPE '|' THEN\r\n N'\r\n MAX(physical_io * recursion) OVER (PARTITION BY session_id, request_id) +\r\n MIN(physical_io * recursion) OVER (PARTITION BY session_id, request_id) AS physical_io_delta,\r\n MAX(reads * recursion) OVER (PARTITION BY session_id, request_id) +\r\n MIN(reads * recursion) OVER (PARTITION BY session_id, request_id) AS reads_delta,\r\n MAX(physical_reads * recursion) OVER (PARTITION BY session_id, request_id) +\r\n MIN(physical_reads * recursion) OVER (PARTITION BY session_id, request_id) AS physical_reads_delta,\r\n MAX(writes * recursion) OVER (PARTITION BY session_id, request_id) +\r\n MIN(writes * recursion) OVER (PARTITION BY session_id, request_id) AS writes_delta,\r\n MAX(tempdb_allocations * recursion) OVER (PARTITION BY session_id, request_id) +\r\n MIN(tempdb_allocations * recursion) OVER (PARTITION BY session_id, request_id) AS tempdb_allocations_delta,\r\n MAX(tempdb_current * recursion) OVER (PARTITION BY session_id, request_id) +\r\n MIN(tempdb_current * recursion) OVER (PARTITION BY session_id, request_id) AS tempdb_current_delta,\r\n MAX(CPU * recursion) OVER (PARTITION BY session_id, request_id) +\r\n MIN(CPU * recursion) OVER (PARTITION BY session_id, request_id) AS CPU_delta,\r\n MAX(thread_CPU_snapshot * recursion) OVER (PARTITION BY session_id, request_id) +\r\n MIN(thread_CPU_snapshot * recursion) OVER (PARTITION BY session_id, request_id) AS thread_CPU_delta,\r\n MAX(context_switches * recursion) OVER (PARTITION BY session_id, request_id) +\r\n MIN(context_switches * recursion) OVER (PARTITION BY session_id, request_id) AS context_switches_delta,\r\n MAX(used_memory * recursion) OVER (PARTITION BY session_id, request_id) +\r\n MIN(used_memory * recursion) OVER (PARTITION BY session_id, request_id) AS used_memory_delta,\r\n MAX(max_used_memory * recursion) OVER (PARTITION BY session_id, request_id) +\r\n MIN(max_used_memory * recursion) OVER (PARTITION BY session_id, request_id) AS max_used_memory_delta,\r\n MIN(last_request_start_time) OVER (PARTITION BY session_id, request_id) AS first_request_start_time, '\r\n ELSE N''\r\n END + N'\r\n COUNT(*) OVER (PARTITION BY session_id, request_id) AS num_events\r\n FROM #sessions AS s1 ' +\r\n CASE\r\n WHEN @sort_order = '' THEN N''\r\n ELSE\r\n N'\r\n ORDER BY ' +\r\n CONVERT(NVARCHAR(MAX), @sort_order)\r\n END +\r\n N'\r\n ) AS s\r\n WHERE\r\n s.recursion = 1\r\n ) x\r\n OPTION (KEEPFIXED PLAN);\r\n ' +\r\n CASE @return_schema\r\n WHEN 1 THEN\r\n N'\r\n SET @schema =\r\n ''CREATE TABLE <table_name> ( '' +\r\n STUFF\r\n (\r\n (\r\n SELECT\r\n '','' +\r\n QUOTENAME(COLUMN_NAME) + '' '' +\r\n DATA_TYPE +\r\n CASE\r\n WHEN DATA_TYPE LIKE ''%char'' THEN ''('' + COALESCE(NULLIF(CONVERT(VARCHAR, CHARACTER_MAXIMUM_LENGTH), ''-1''), ''max'') + '') ''\r\n ELSE '' ''\r\n END +\r\n CASE IS_NULLABLE\r\n WHEN ''NO'' THEN ''NOT ''\r\n ELSE ''''\r\n END + ''NULL'' AS [text()]\r\n FROM tempdb.INFORMATION_SCHEMA.COLUMNS\r\n WHERE\r\n TABLE_NAME = (SELECT name FROM tempdb.sys.objects WHERE object_id = OBJECT_ID(''tempdb..#session_schema''))\r\n ORDER BY\r\n ORDINAL_POSITION\r\n FOR XML\r\n PATH('''')\r\n ), +\r\n 1,\r\n 1,\r\n ''''\r\n ) +\r\n '');''; '\r\n ELSE N''\r\n END;\r\n --End derived table and INSERT specification\r\n\r\n EXEC sp_executesql\r\n @sql_n,\r\n N'@num_data_threshold MONEY, @schema VARCHAR(MAX) OUTPUT',\r\n @num_data_threshold, @schema OUTPUT;\r\nEND;\r\nGO\r\n"
}
{
"id": "c17af2fe-3595-4d52-a31a-85d89e8ce67d",
"prefix": "TDC_mvpYK_Helper_LongPrint",
"description": "Helper_LongPrint (By Yildirim Kocdag)",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:26.0046855Z",
"permissions": [],
"body": "IF OBJECT_ID('dbo.Helper_LongPrint', 'P') IS NOT NULL\r\n\tDROP PROCEDURE dbo.Helper_LongPrint;\r\nGO\r\n\r\nCREATE PROCEDURE dbo.Helper_LongPrint (@string NVARCHAR(MAX))\r\nAS\r\nBEGIN\r\n\tSET NOCOUNT ON;\r\n\tSET @string = RTRIM(@string);\r\n\t--\r\n\tDECLARE @cr CHAR(1), @lf CHAR(1);\r\n\tSET @cr = CHAR(13); SET @lf = CHAR(10);\r\n\t--\r\n\tDECLARE @len INT,\r\n\t\t@cr_index INT,\r\n\t\t@lf_index INT,\r\n\t\t@crlf_index INT,\r\n\t\t@has_cr_and_lf BIT,\r\n\t\t@left NVARCHAR(4000),\r\n\t\t@reverse NVARCHAR(4000);\r\n\t--\r\n\tSET @len = 4000;\r\n\t--\r\n\tWHILE (LEN(@string) > @len)\r\n\tBEGIN\r\n\t\tSET @left = LEFT(@string, @len);\r\n\t\tSET @reverse = REVERSE(@left);\r\n\t\tSET @cr_index = @len - CHARINDEX(@cr, @reverse) + 1;\r\n\t\tSET @lf_index = @len - CHARINDEX(@lf, @reverse) + 1;\r\n\t\tSET @crlf_index = CASE WHEN @cr_index < @lf_index THEN @cr_index ELSE @lf_index END;\r\n\t\tSET @has_cr_and_lf = CASE WHEN @cr_index < @len AND @lf_index < @len THEN 1 ELSE 0 END;\r\n\t\t--\r\n\t\tPRINT LEFT(@string, @crlf_index - 1);\r\n\t\t--\r\n\t\tSET @string = RIGHT(@string, LEN(@string) - @crlf_index - @has_cr_and_lf);\r\n\tEND;\r\n\t--\r\n\tPRINT @string;\r\nEND;\r\nGO"
}
{
"id": "460af147-a9fb-441a-9252-a71d303cf5ad",
"prefix": "TDC_MyRolesAndPermissions",
"description": "",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:26.0046855Z",
"permissions": [],
"body": "-- my roles\r\nSELECT [level] = 'SERVER', name, [is_member] = IS_SRVROLEMEMBER(name) \r\nFROM sys.server_principals WHERE type = 'R'\r\nUNION \r\nSELECT [level] = 'DATABASE', name, [is_member] = IS_MEMBER(name) \r\nFROM sys.database_principals WHERE type = 'R'\r\n\r\n-- my permissions\r\nSELECT [level] = 'SERVER', * FROM sys.fn_my_permissions(NULL, 'SERVER')\r\nUNION \r\nSELECT [level] = 'DATABASE', * FROM sys.fn_my_permissions(NULL, 'DATABASE')"
}
{
"id": "733386ea-ba75-4bfc-97bb-0937fdf66d67",
"prefix": "TDC_Plan_ClearSingleUsePlansFromCache",
"description": "",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:26.0046855Z",
"permissions": [],
"body": "DECLARE @Sql VARCHAR(MAX) = (\r\n\tSELECT 'DBCC FREEPROCCACHE (0x' + CONVERT( VARCHAR(MAX), [ecp].[plan_handle], 2) + ') WITH NO_INFOMSGS; ' + CHAR(10)\r\n\tFROM [sys].[dm_exec_cached_plans] [ecp]\r\n\tWHERE [ecp].[usecounts] = 1\r\n\t\t\tAND [ecp].[objtype] IN('Adhoc', 'Prepared')\r\n\tFOR XML PATH('')\r\n);\r\n\r\nSELECT @sql\r\nEXEC (@sql)"
}
{
"id": "aec4cd34-8049-46a3-ab95-b1d20f78ecfc",
"prefix": "TDC_Plan_DidNotCompileProperly",
"description": "",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:26.0046855Z",
"permissions": [],
"body": "-- https://www.brentozar.com/blitzcache/compilation-timeout/\r\n\r\n\r\nWITH XMLNAMESPACES('http://schemas.microsoft.com/sqlserver/2004/07/showplan' AS p)\r\nSELECT [db_name] = DB_NAME(qp.[dbid]), \r\n\ttimeout_statement = CASE\r\n\t\tWHEN qs.statement_end_offset > 0\r\n\t\tTHEN substring(st.text, qs.statement_start_offset/2 + 1, (qs.statement_end_offset - qs.statement_start_offset) / 2)\r\n\t\tELSE 'SQL Statement'\r\n END,\r\n st.text AS batch,\r\n qp.query_plan,\r\n\tqs.[execution_count], \r\n\t[avg_elapsed_time] = CONVERT(varchar(30), DATEADD(millisecond, ([qs].[total_elapsed_time] / qs.[execution_count] / 1000.0), 0), 114), \r\n\t[avg_worker_time] = CONVERT(varchar(30), DATEADD(millisecond, ([qs].[total_worker_time] / qs.[execution_count] / 1000.0), 0), 114),\r\n\t[avg_logical_reads] = [qs].[total_logical_reads] / qs.[execution_count], \r\n\t[avg_logical_writes] = [qs].[total_logical_writes] / qs.[execution_count],\r\n\t[avg_grant_mb] = CAST(qs.[total_grant_kb] / 1024.0 AS decimal(19,2)),\r\n\t[avg_grant_used_mb] = CAST(qs.[total_used_grant_kb] / 1024.0 AS decimal(19,2))\r\nFROM (\r\n SELECT TOP 50 *\r\n FROM sys.dm_exec_query_stats\r\n ORDER BY total_worker_time DESC\r\n) AS qs\r\nCROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st\r\nCROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp\r\nWHERE qp.query_plan.exist('//p:StmtSimple/@StatementOptmEarlyAbortReason[.=\"TimeOut\" or .=\"MemoryLimitExceeded\"]') = 1\r\n"
}
{
"id": "29d15442-b85d-4e02-b89a-270a8b01a088",
"prefix": "TDC_Plan_FindImplicitConversions",
"description": "",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:26.0056849Z",
"permissions": [],
"body": "--http://sqlmag.com/database-performance-tuning/sql-server-plan-cache-junk-drawer-your-queries\r\n\r\n--Find Plans with Implicit Conversion Warnings\r\n;WITH XMLNAMESPACES(DEFAULT N'http://schemas.microsoft.com/sqlserver/2004/07/showplan')\r\nSELECT TOP 500 cp.query_hash, cp.query_plan_hash,\r\n ConvertIssue = operators.value('@ConvertIssue','nvarchar(250)'),\r\n Expression = operators.value('@Expression','nvarchar(250)'), qp.query_plan\r\nFROM sys.dm_exec_query_stats cp\r\nCROSS APPLY sys.dm_exec_query_plan(cp.plan_handle) qp\r\nCROSS APPLY query_plan.nodes('//Warnings/PlanAffectingConvert') rel(operators)\r\n"
}
{
"id": "d1690062-e770-4041-b63f-6e2d9eb132ad",
"prefix": "TDC_Plan_FindKeyLookups",
"description": "",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:26.0056849Z",
"permissions": [],
"body": "--http://sqlmag.com/database-performance-tuning/sql-server-plan-cache-junk-drawer-your-queries\r\n\r\n\r\n--Find Plans with Key Lookup and Clustered Index Seek Operators\r\n;WITH XMLNAMESPACES(DEFAULT N'http://schemas.microsoft.com/sqlserver/2004/07/showplan')\r\nSELECT TOP 500 cp.query_hash, cp.query_plan_hash,\r\n PhysicalOperator = operators.value('@PhysicalOp','nvarchar(50)'),\r\n LogicalOp = operators.value('@LogicalOp','nvarchar(50)'),\r\n AvgRowSize = operators.value('@AvgRowSize','nvarchar(50)'),\r\n EstimateCPU = operators.value('@EstimateCPU','nvarchar(50)'),\r\n EstimateIO = operators.value('@EstimateIO','nvarchar(50)'),\r\n EstimateRebinds = operators.value('@EstimateRebinds','nvarchar(50)'),\r\n EstimateRewinds = operators.value('@EstimateRewinds','nvarchar(50)'),\r\n EstimateRows = operators.value('@EstimateRows','nvarchar(50)'),\r\n Parallel = operators.value('@Parallel','nvarchar(50)'),\r\n NodeId = operators.value('@NodeId','nvarchar(50)'),\r\n EstimatedTotalSubtreeCost = operators.value('@EstimatedTotalSubtreeCost','nvarchar(50)'), qp.query_plan\r\nFROM sys.dm_exec_query_stats cp\r\nCROSS APPLY sys.dm_exec_query_plan(cp.plan_handle) qp\r\nCROSS APPLY query_plan.nodes('//RelOp') rel(operators)"
}
{
"id": "be39273b-0eb0-4f29-bcc7-d71fee73246a",
"prefix": "TDC_Plan_FindMissingIndex",
"description": "",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:26.0056849Z",
"permissions": [],
"body": "--http://sqlmag.com/database-performance-tuning/sql-server-plan-cache-junk-drawer-your-queries\r\n\r\n--find plans woth suggested missing indexes\r\n;WITH XMLNAMESPACES(DEFAULT N'http://schemas.microsoft.com/sqlserver/2004/07/showplan')\r\nSELECT top 500 dec.usecounts, dec.refcounts, dec.objtype\r\n , dec.cacheobjtype, des.dbid, des.text,deq.query_plan\r\nFROM sys.dm_exec_cached_plans AS dec\r\nCROSS APPLY sys.dm_exec_sql_text(dec.plan_handle) AS des\r\nCROSS APPLY sys.dm_exec_query_plan(dec.plan_handle) AS deq\r\nWHERE deq.query_plan.exist(N'/ShowPlanXML/BatchSequence/Batch/Statements/StmtSimple/QueryPlan/MissingIndexes/MissingIndexGroup') <> 0\r\nORDER BY dec.usecounts DESC\r\n"
}
{
"id": "06590c2a-787d-4490-aeac-1c810ea6cc8a",
"prefix": "TDC_Plan_HighCompileTime",
"description": "",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:26.0056849Z",
"permissions": [],
"body": "-- https://www.sqlskills.com/blogs/jonathan/identifying-high-compile-time-statements-from-the-plan-cache/\r\n\r\nSET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;\r\nWITH XMLNAMESPACES (\r\n DEFAULT 'http://schemas.microsoft.com/sqlserver/2004/07/showplan'\r\n)\r\nSELECT TOP 10\r\n CompileTime_ms,\r\n CompileCPU_ms,\r\n CompileMemory_KB,\r\n qs.execution_count,\r\n qs.total_elapsed_time / 1000 AS duration_ms,\r\n qs.total_worker_time / 1000 AS cputime_ms,\r\n (qs.total_elapsed_time / qs.execution_count) / 1000 AS avg_duration_ms,\r\n (qs.total_worker_time / qs.execution_count) / 1000 AS avg_cputime_ms,\r\n qs.max_elapsed_time / 1000 AS max_duration_ms,\r\n qs.max_worker_time / 1000 AS max_cputime_ms,\r\n SUBSTRING( st.text,\r\n (qs.statement_start_offset / 2) + 1,\r\n (CASE qs.statement_end_offset\r\n WHEN -1 THEN\r\n DATALENGTH(st.text)\r\n ELSE\r\n qs.statement_end_offset\r\n END - qs.statement_start_offset\r\n ) / 2 + 1\r\n ) AS StmtText,\r\n query_hash,\r\n query_plan_hash\r\nFROM\r\n(\r\n SELECT c.value('xs:hexBinary(substring((@QueryHash)[1],3))', 'varbinary(max)') AS QueryHash,\r\n c.value('xs:hexBinary(substring((@QueryPlanHash)[1],3))', 'varbinary(max)') AS QueryPlanHash,\r\n c.value('(QueryPlan/@CompileTime)[1]', 'int') AS CompileTime_ms,\r\n c.value('(QueryPlan/@CompileCPU)[1]', 'int') AS CompileCPU_ms,\r\n c.value('(QueryPlan/@CompileMemory)[1]', 'int') AS CompileMemory_KB,\r\n qp.query_plan\r\n FROM sys.dm_exec_cached_plans AS cp\r\n CROSS APPLY sys.dm_exec_query_plan(cp.plan_handle) AS qp\r\n CROSS APPLY qp.query_plan.nodes('ShowPlanXML/BatchSequence/Batch/Statements/StmtSimple') AS n(c)\r\n) AS tab\r\nJOIN sys.dm_exec_query_stats AS qs\r\n ON tab.QueryHash = qs.query_hash\r\nCROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st\r\nORDER BY CompileTime_ms DESC\r\nOPTION (RECOMPILE, MAXDOP 1);"
}
{
"id": "de252a5e-1aa8-49a4-87b2-8ca2a6e9d0a6",
"prefix": "TDC_Plan_QueriesWithFunctions",
"description": "",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:26.0066853Z",
"permissions": [],
"body": "-- https://www.red-gate.com/simple-talk/sql/performance/the-seven-sins-against-tsql-performance/\r\n\r\nSELECT OBJECT_SCHEMA_NAME(o.object_id, DB_ID()) + '.' + o.name AS object_name, \r\n\to.type_desc,\r\n\tdeqp.query_plan,\r\n\tdest.text,\r\n\tactualstatement = SUBSTRING (\r\n\t\t\t\t\t\t\tdest.text,\r\n\t\t\t\t\t\t\t(deqs.statement_start_offset / 2) + 1,\r\n\t\t\t\t\t\t\t(deqs.statement_end_offset - deqs.statement_start_offset) / 2 + 1\r\n\t\t\t\t\t\t)\r\nFROM sys.dm_exec_query_stats deqs\r\nCROSS APPLY sys.dm_exec_query_plan(deqs.plan_handle) deqp\r\nCROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) dest\r\nINNER JOIN sys.objects o ON deqp.objectid = o.object_id\r\nWHERE o.type IN ('FN', 'TF') -- FN = SQL scalar function, TF = SQL table-valued-function"
}
{
"id": "eb2a5432-edd6-49cd-b3e4-1b6afe07acfd",
"prefix": "TDC_Plan_SingleUse",
"description": "",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:26.0066853Z",
"permissions": [],
"body": "--http://sqlmag.com/database-performance-tuning/sql-server-plan-cache-junk-drawer-your-queries\r\n\r\n\r\n--Find Single-Use Plans\r\nSELECT top 500 text, cp.objtype, cp.size_in_bytes, qp.query_plan\r\nFROM sys.dm_exec_cached_plans AS cp\r\nCROSS APPLY sys.dm_exec_sql_text(cp.plan_handle) st\r\nCROSS APPLY sys.dm_exec_query_plan(cp.plan_handle) qp\r\nWHERE cp.cacheobjtype = N'Compiled Plan'\r\n AND cp.objtype IN(N'Adhoc', N'Prepared')\r\n AND cp.usecounts = 1\r\nORDER BY cp.size_in_bytes DESC\r\nOPTION (RECOMPILE);"
}
{
"id": "4efc2b05-6742-4104-9539-a535e3a2d95e",
"prefix": "TDC_PrintInstantly",
"description": "Print Statement Instantly using RaiseError",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:26.0066853Z",
"permissions": [],
"body": "RAISERROR('$string$', 0, 1) WITH NOWAIT;\n",
"placeholders": [
{
"name": "string",
"defaultValue": null
}
]
}
{
"id": "a7026fff-e2f8-4d12-9bf0-4ed2c81ca95f",
"prefix": "TDC_ReadErrorLog",
"description": "Read Error Log",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:26.0066853Z",
"permissions": [],
"body": "-- https://www.mssqltips.com/sqlservertip/1476/reading-the-sql-server-log-files-using-tsql/\n\nIF OBJECT_ID('tempdb..#TmpErrorLog') IS NOT NULL BEGIN\n DROP TABLE #TmpErrorLog\nEND\n\nCREATE TABLE #TmpErrorLog (\n\t[LogDate] DATETIME NULL,\n\t[ProcessInfo] VARCHAR(20) NULL,\n\t[Text] VARCHAR(MAX) NULL \n)\n\nINSERT INTO #TmpErrorLog ([LogDate], [ProcessInfo], [Text])\nEXEC sp_readerrorlog \n @p1 = 0,\t\t-- Value of error log file you want to read: 0 = current, 1 = Archive #1, 2 = Archive #2, etc...\n @p2 = NULL,\t-- Log file type: 1 or NULL = error log, 2 = SQL Agent log \n @p3 = NULL,\t-- Search string 1: String one you want to search for\n @p4 = NULL\t-- Search string 2: String two you want to search for to further refine the results\n\nSELECT [RowNbr] = ROW_NUMBER() OVER (PARTITION BY [tel].[ProcessInfo] ORDER BY [tel].[LogDate]), * \nFROM [#TmpErrorLog] tel \nWHERE [tel].[LogDate] >= CAST(GETDATE() AS DATE)\n\t--AND [tel].[Text] LIKE '%DBCC%'\nORDER BY [tel].[LogDate]\n \n\nIF OBJECT_ID('tempdb..#TmpErrorLog') IS NOT NULL BEGIN\n DROP TABLE #TmpErrorLog\nEND\n\n\n\n\n\n"
}
{
"id": "aa6c03e5-67ed-4759-9ff8-a13638d56c5b",
"prefix": "TDC_Region",
"description": "Region",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:26.0076852Z",
"permissions": [],
"body": "--$BeginRegion: $NewRegionName$\r\n$PASTE$\r\n--$EndRegion: $NewRegionName$",
"placeholders": [
{
"name": "NewRegionName",
"defaultValue": null
}
]
}
{
"id": "9742e127-1110-4a24-a2d8-f7c51a421280",
"prefix": "TDC_RunBlitz",
"description": "",
"status": "pendingShared",
"lastModified": "2022-11-22T17:09:23.1903377Z",
"permissions": [],
"body": "\r\nDBCC TRACEON(7412, -1); \r\nEXEC [dbo].[sp_BlitzWho] @ShowSleepingSPIDs = 1, @GetLiveQueryPlan = 1, @ExpertMode = 1; \r\nDBCC TRACEOFF(7412, -1);\r\n\r\nEXEC [dbo].[sp_BlitzFirst] @ExpertMode = 1, @CheckProcedureCache = 1\r\n\r\nEXEC [dbo].[sp_Blitz] @CheckProcedureCache = 1, @BringThePain = 1, @UsualDBOwner = 'sa' \r\n\r\nEXEC [dbo].[sp_BlitzCache] @BringThePain = 1 \r\n\r\nEXEC [dbo].[sp_BlitzIndex] @Mode = 4, @BringThePain = 1, @ShowAllMissingIndexRequests=1"
}
{
"id": "8ce8163a-fab7-4cce-8e51-be652bfa22f8",
"prefix": "TDC_ScanDatabaseForValue",
"description": "",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:26.0076852Z",
"permissions": [],
"body": "/*\r\n\tAuthors: Tim Cartwright, Matthew Naul\r\n\tPurpose: Scan a database for all columns that contain a value. \r\n\tThe LIKE keyword is used, so wildcard matching will work. \r\n\tQueries are batched together by table up to N rows at a time. Like so:\r\n\t\tSELECT * FROM TBL WHERE COL1 LIKE @lookfor\r\n\t\tUNION ALL\r\n\t\tSELECT * FROM TBL WHERE COL2 LIKE @lookfor\r\n\t\tUNION ALL\r\n\t\tSELECT * FROM TBL WHERE COL3 LIKE @lookfor\r\n\t\t...\r\n\t\r\n\tUp to N columns. If a table has more than N columns, then the query will be broken apart.\r\n\tParameters:\r\n\t\t@lookFor: The value to look for in the columns\r\n\t\t@lookForType: They type of data that is being looked for. Valid values: numeric / string\r\n\t\t@includeMaxLengthColumns: If 1, then scan max length columns, else exclude them. Can make the query run much slower if max length columns are scanned.\r\n\tUsage: \r\n\t\tChange the @lookfor variable and execute.\r\n*/\r\n\r\nSET NOCOUNT ON\r\nGO\r\nDECLARE\t@lookFor VARCHAR(1024) = '$lookfor$%',\r\n\t@lookForType VARCHAR(10) = 'string', -- Valid values: numeric / string\r\n\t@includeMaxLengthColumns BIT = 0\r\n\r\nIF OBJECT_ID('tempdb..#results') IS NOT NULL BEGIN \r\n\tDROP TABLE #results \r\nEND\r\n\r\nIF OBJECT_ID('tempdb..#tmpSelects') IS NOT NULL BEGIN \r\n\tDROP TABLE #tmpSelects \r\nEND\r\n\r\nCREATE TABLE #results (\r\n\tServerName\tsysname,\r\n\tDbName\tsysname,\r\n\tSchemaName sysname,\r\n\tTableName\tsysname,\r\n\tColumnName\tsysname,\r\n\tValue VARCHAR(max)\r\n)\r\n\r\nCREATE TABLE #tmpSelects (\r\n\tid INT NOT NULL PRIMARY KEY IDENTITY,\r\n\tSchemaName sysname,\r\n\tTableName sysname,\r\n\tColumnName sysname,\r\n\tQuery NVARCHAR(max)\r\n)\r\n\r\nDECLARE\t@serverName NVARCHAR(1024) = @@SERVERNAME,\r\n\t@sql NVARCHAR(MAX) = N'', \r\n\t@CurrentTableName sysname,\r\n\t@lastId INT, \r\n\t@maxRows INT = 10\r\n \r\n-- if we are on a AG, and we have rights, try to get the real server name\r\nIF HAS_PERMS_BY_NAME(null, null, 'VIEW SERVER STATE') = 1 BEGIN\r\n\tSET @serverName = (SELECT ISNULL((\r\n\t\t\tSELECT dns_name + ISNULL('\\' + CAST(SERVERPROPERTY('InstanceName') AS VARCHAR(512)), '')\r\n\t\t\tFROM sys.availability_group_listeners agl\r\n\t\t\tJOIN sys.availability_group_listener_ip_addresses aglip\r\n\t\t\t\tON agl.listener_id = aglip.listener_id\r\n\t\t\tJOIN sys.dm_exec_connections c\r\n\t\t\t\tON aglip.ip_address = c.local_net_address\r\n\t\t\tWHERE session_id = @@SPID\r\n\t\t), @@SERVERNAME))\r\nEND\r\n\r\nINSERT INTO #tmpSelects (\r\n\tSchemaName, \r\n\tTableName,\r\n\tColumnName,\r\n Query\r\n)\r\nSELECT OBJECT_SCHEMA_NAME(t.object_id), t.name, c.name, \r\n\t[Query] = N'SELECT [ServerName] = ''' + @serverName \r\n\t+ ''', [DbName] = DB_NAME(), [SchemaName] = ''' + OBJECT_SCHEMA_NAME(t.object_id) + ''', [TableName] = ''' \r\n\t+ t.name + ''', [ColumnName] = ''' + c.name + ''', [Value] = CAST([' + c.name + '] AS VARCHAR(MAX)) FROM [' \r\n\t+ OBJECT_SCHEMA_NAME(t.object_id) + '].[' + t.name + '] WHERE [' \r\n\t+ c.name + '] LIKE @lookfor UNION ALL ' + CHAR(13) + CHAR(10)\r\nFROM sys.tables t \r\nINNER JOIN sys.columns c ON c.object_id = t.object_id\r\nINNER JOIN sys.types typ ON typ.system_type_id = c.system_type_id\r\nWHERE t.is_ms_shipped = 0 \r\n\tAND c.is_identity = 0 \r\n\tAND c.is_computed = 0\r\n\tAND c.is_filestream = 0\r\n\tAND t.name NOT LIKE 'H_%' -- ignore history tables, ours start with H_\r\n\tAND t.name NOT LIKE '%History' -- ignore history tables, another naming convention\r\n\tAND CASE \r\n\t\tWHEN @lookForType = 'numeric' AND typ.name IN ('tinyint','smallint','int','real','money','float','sql_variant','decimal','numeric','smallmoney','bigint') THEN 1\r\n\t\tWHEN @lookForType = 'string' AND typ.name IN ('sql_variant','varchar','char','nvarchar','nchar','sysname') THEN 1\r\n\t\tELSE 0\r\n\tEND = 1\r\n\tAND (@includeMaxLengthColumns = 1 OR c.max_length <> -1) \r\nORDER BY OBJECT_SCHEMA_NAME(t.object_id), t.name\r\n\r\n--SELECT * FROM #tmpSelects\r\n\r\nSELECT @sql += t.Query, \r\n\t@lastId = id, \r\n\t@CurrentTableName = t.TableName\r\nFROM (\r\n\tSELECT TOP (@maxRows) id,\r\n\t\tQuery,\r\n\t\tTableName, \r\n\t\tCurrentRank = DENSE_RANK() OVER (ORDER BY SchemaName, TableName)\t\r\n\tFROM #tmpSelects \r\n) t WHERE t.CurrentRank = 1\r\n-- strip off the last union \r\nSET @sql = LEFT(@sql, LEN(@sql) - 12)\r\n\r\n--SELECT @sql, @lastId, @CurrentTableName\r\n-- sanity counter\r\nDECLARE @cntr INT = 0\r\n\r\nWHILE @sql IS NOT NULL AND LEN(@sql) > 0 BEGIN\r\n\tINSERT INTO #results (\r\n\t ServerName,\r\n\t DbName,\r\n\t\tSchemaName,\r\n\t TableName,\r\n\t ColumnName,\r\n\t\tValue\r\n\t)\r\n\tEXEC sys.sp_executesql @stmt = @sql, @params = N'@lookfor VARCHAR(1024)', @lookfor = @lookfor\r\n\r\n\tDELETE FROM #tmpSelects WHERE id <= @lastId\r\n\tSET @sql = N''\r\n\r\n\tSELECT @sql += t.Query, \r\n\t\t@lastId = id, \r\n\t\t@CurrentTableName = t.TableName\r\n\tFROM (\r\n\t\tSELECT TOP (@maxRows) id,\r\n\t\t\tQuery,\r\n\t\t\tTableName,\r\n\t\t\tCurrentRank = DENSE_RANK() OVER (ORDER BY SchemaName, TableName)\t\r\n\t\tFROM #tmpSelects \r\n\t) t WHERE t.CurrentRank = 1\r\n\r\n\tIF @sql IS NULL OR LEN(@sql) = 0 BREAK;\r\n\tPRINT @CurrentTableName\r\n\r\n\t-- strip off the last union \r\n\tSET @sql = LEFT(@sql, LEN(@sql) - 12)\r\n\r\n\tIF @cntr > 10000 BEGIN PRINT 'SANITY COUNTER BREAK!!!'; BREAK; END\r\n\tSET @cntr += 1\r\nEND\r\n\r\nSELECT ServerName,\r\n\tDbName,\r\n\tSchemaName,\r\n\tTableName,\r\n\tColumnName,\r\n\tValue,\r\n\t[SelectQuery] = 'SELECT * FROM [' + DbName + '].[' + SchemaName + '].[' + TableName + '] WHERE [' + ColumnName + '] = ''' + Value + ''''\r\nFROM #results",
"placeholders": [
{
"name": "lookfor",
"defaultValue": null
}
]
}
{
"id": "19a23a5f-9b18-4ba8-9122-d6541fd9808b",
"prefix": "TDC_Search",
"description": "Search String In Objects",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:26.0076852Z",
"permissions": [],
"body": "DECLARE @SearchPattern NVARCHAR(128) = N'%$string$%';\r\n--\r\nSELECT SCHEMA_NAME(O.schema_id) AS \"Schema\",\r\n\t O.name AS \"Name\",\r\n\t O.type AS \"Type\",\r\n\t '[' + SCHEMA_NAME(O.schema_id) + '].[' + O.name + ']' AS \"FullName\",\r\n\t OBJECT_DEFINITION(O.object_id) AS \"Source\"\r\nFROM sys.objects AS O\r\nWHERE LOWER(OBJECT_DEFINITION(O.object_id)) LIKE LOWER(@SearchPattern)\r\n\t AND O.type IN (\t'C', -- = Check Constraint\r\n\t\t\t\t\t\t'D', -- = Default (Constraint or Standalone)\r\n\t\t\t\t\t\t'P', -- = SQL Stored Procedure\r\n\t\t\t\t\t\t'FN', -- = SQL Scalar Function\r\n\t\t\t\t\t\t'R', -- = Rule\r\n\t\t\t\t\t\t'RF', -- = Replication Filter Procedure\r\n\t\t\t\t\t\t'TR', -- = SQL Trigger (schema-scoped DML trigger, or DDL trigger at either the database or server scope)\r\n\t\t\t\t\t\t'IF', -- = SQL Inline Table-Valued Function\r\n\t\t\t\t\t\t'TF', -- = SQL Table-Valued Function\r\n\t\t\t\t\t\t'V'\r\n\t\t\t\t\t) -- = View\r\nUNION ALL\r\nSELECT SCHEMA_NAME(Q.schema_id) AS \"Schema\",\r\n\t Q.name AS \"Name\",\r\n\t 'SQ' AS \"Type\",\r\n\t '[' + SCHEMA_NAME(Q.schema_id) + '].[' + Q.name + ']' AS \"FullName\",\r\n\t Q.activation_procedure AS \"Source\"\r\nFROM sys.service_queues AS Q\r\nWHERE Q.activation_procedure LIKE LOWER(@SearchPattern)\r\nORDER BY O.type,\r\n\t\t O.name;\r\n",
"placeholders": [
{
"name": "string",
"defaultValue": null
}
]
}
{
"id": "1d5649e3-97aa-4b94-a2a6-05658a343bf7",
"prefix": "TDC_SearchTablesForString_v1",
"description": "Search All Tables which Contain Text Columns like %char% and %text%",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:26.0076852Z",
"permissions": [],
"body": "/* =========================================================================================================================================\r\n-- Server\t\t: Local Server\r\n-- Database\t\t: User Database\r\n-- Script\t\t: SearchTablesForString_v1\r\n-- Description\t: Search All Tables which Contain Text Columns like %char% and %text%.\r\n-- Usage\t\t: Most Efficient for Smaller Tables Having TableRowCount <= 100000.\r\n========================================================================================================================================= */\r\nDECLARE @SearchString VARCHAR(1024);\r\nSET @SearchString='$StringToSearch$'; --Provide the String here.\r\n--\r\n/* === DO NOT CHANGE BELOW CODE FROM HERE =============================================================================================== */\r\nSET NOCOUNT ON;\r\n--$BeginRegion: SearchResultSet TableVariable\r\nDECLARE @SearchResults TABLE\r\n(\r\n\tDatabaseName VARCHAR(256) NULL,\r\n\tSchemaName VARCHAR(256) NULL,\r\n\tTableName VARCHAR(256) NULL,\r\n\tColumnName VARCHAR(256) NULL,\r\n\tColumnDataType VARCHAR(256) NULL,\r\n\tTableRowCount INT NULL,\r\n\tStringOccuranceCount INT NULL\r\n);\r\n--$EndRegion: SearchResultSet TableVariable\r\n--\r\n--$BeginRegion: SearchTableColumn_Cursor\r\nDECLARE @DBname VARCHAR(256), @SCHname VARCHAR(256), @TBLname VARCHAR(256), @COLname VARCHAR(256), @COLdatatype VARCHAR(256);\r\n--\r\nDECLARE @SQLcmd NVARCHAR(MAX) =NULL;\r\n--\r\nDECLARE SearchTableColumn_Cursor CURSOR LOCAL FAST_FORWARD FOR\r\nSELECT COL.TABLE_CATALOG, COL.TABLE_SCHEMA, COL.TABLE_NAME, COL.COLUMN_NAME, COL.DATA_TYPE\r\nFROM INFORMATION_SCHEMA.COLUMNS AS COL\r\nINNER JOIN INFORMATION_SCHEMA.TABLES AS TBL ON TBL.TABLE_SCHEMA=COL.TABLE_SCHEMA AND TBL.TABLE_NAME=COL.TABLE_NAME \r\nWHERE TBL.TABLE_TYPE='BASE TABLE' AND COL.DATA_TYPE LIKE '%char%' OR COL.DATA_TYPE LIKE '%text%';\r\n--\r\nOPEN SearchTableColumn_Cursor;\r\nFETCH NEXT FROM SearchTableColumn_Cursor INTO @DBname, @SCHname, @TBLname, @COLname, @COLdatatype;\r\n--\r\nWHILE @@FETCH_STATUS=0 BEGIN\r\n\tSET @SQLcmd --\r\n\t\t=N'SELECT '''+@DBname+N''' AS \"DatabaseName\",'+CHAR(10) --\r\n\t\t +N'\t'''+@SCHname+N''' AS \"SchemaName\",'+CHAR(10) --\r\n\t\t +N'\t'''+@TBLname+N''' AS \"TableName\",'+CHAR(10) --\r\n\t\t +N'\t'''+@COLname+N''' AS \"ColumnName\",'+CHAR(10) --\r\n\t\t +N'\t'''+@COLdatatype+N''' AS \"ColumnDataType\",'+CHAR(10) --\r\n\t\t +N'\t(SELECT COUNT(1) FROM ['+@DBname+N'].['+@SCHname+N'].['+@TBLname+N'] WITH (NOLOCK)) AS \"TableRowCount\",'+CHAR(10) --\r\n\t\t +N'\tCOUNT(1) AS \"StringOccuranceCount\"'+CHAR(10) --\r\n\t\t +N'FROM ['+@DBname+N'].['+@SCHname+N'].['+@TBLname+N'] WITH (NOLOCK)'+CHAR(10) --\r\n\t\t +N'WHERE ['+@COLname+N'] LIKE ''%'+@SearchString+N'%'';';\r\n\t--\r\n\t--PRINT @SQLcmd;\r\n\tINSERT INTO @SearchResults(DatabaseName, SchemaName, TableName, ColumnName, ColumnDataType, TableRowCount, StringOccuranceCount)\r\n\tEXEC sys.sp_executesql @command = @SQLcmd;\r\n\t--\r\n\tFETCH NEXT FROM SearchTableColumn_Cursor INTO @DBname, @SCHname, @TBLname, @COLname, @COLdatatype;\r\nEND;\r\nCLOSE SearchTableColumn_Cursor;\r\nDEALLOCATE SearchTableColumn_Cursor;\r\n--$EndRegion: SearchTableColumn_Cursor\r\n--\r\nSELECT DatabaseName, SchemaName, TableName, ColumnName, ColumnDataType, TableRowCount, StringOccuranceCount,\r\n\t('SELECT * FROM ['+DatabaseName+'].['+SchemaName+'].['+TableName+'] WHERE ['+ColumnName+'] LIKE ''%'+@SearchString+'%''') AS SearchQuery\r\nFROM @SearchResults\r\nWHERE StringOccuranceCount<>0;",
"placeholders": [
{
"name": "StringToSearch",
"defaultValue": null
}
]
}
{
"id": "bb27a020-8bb4-424d-b4a3-451f1dc1b4d7",
"prefix": "TDC_SearchTablesForString_v2",
"description": "Search All Large Tables which Contain Text Columns like %char% and %text%",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:26.0086854Z",
"permissions": [],
"body": "/* =========================================================================================================================================\r\n-- Server\t\t: Local Server\r\n-- Database\t\t: User Database\r\n-- Script\t\t: SearchTablesForString_v2\r\n-- Description\t: Search All Tables which Contain Text Columns like %char% and %text%.\r\n-- Usage\t\t: Most Efficient for Larger Tables Having TableRowCount >= 100000.\r\n========================================================================================================================================= */\r\nDECLARE @SearchString VARCHAR(1024);\r\nSET @SearchString='$StringToSearch$'; --Provide the String here.\r\n--\r\n/* === DO NOT CHANGE BELOW CODE FROM HERE =============================================================================================== */\r\nSET NOCOUNT ON;\r\n--$BeginRegion: SearchResultSet TableVariable\r\nPRINT --\r\nN'IF OBJECT_ID(''tempdb..#SearchResults'',''U'') IS NOT NULL\r\n\tDROP TABLE #SearchResults;\r\nGO\r\nCREATE TABLE #SearchResults\r\n(\r\n\tDatabaseName VARCHAR(256) NULL,\r\n\tSchemaName VARCHAR(256) NULL,\r\n\tTableName VARCHAR(256) NULL,\r\n\tColumnName VARCHAR(256) NULL,\r\n\tColumnDataType VARCHAR(256) NULL,\r\n\tTableRowCount INT NULL,\r\n\tStringOccuranceCount INT NULL\r\n);\r\nGO';\r\nPRINT '--';\r\n--$EndRegion: SearchResultSet TableVariable\r\n--\r\n--$BeginRegion: SearchTableColumn_Cursor\r\nDECLARE @DBname VARCHAR(256), @SCHname VARCHAR(256), @TBLname VARCHAR(256), @COLname VARCHAR(256), @COLdatatype VARCHAR(256);\r\n--\r\nDECLARE @SQLcmd NVARCHAR(MAX) =NULL;\r\n--\r\nDECLARE SearchTableColumn_Cursor CURSOR LOCAL FAST_FORWARD FOR\r\nSELECT COL.TABLE_CATALOG, COL.TABLE_SCHEMA, COL.TABLE_NAME, COL.COLUMN_NAME, COL.DATA_TYPE\r\nFROM INFORMATION_SCHEMA.COLUMNS AS COL\r\nINNER JOIN INFORMATION_SCHEMA.TABLES AS TBL ON TBL.TABLE_SCHEMA=COL.TABLE_SCHEMA AND TBL.TABLE_NAME=COL.TABLE_NAME \r\nWHERE TBL.TABLE_TYPE='BASE TABLE' AND COL.DATA_TYPE LIKE '%char%' OR COL.DATA_TYPE LIKE '%text%';\r\n--\r\nOPEN SearchTableColumn_Cursor;\r\nFETCH NEXT FROM SearchTableColumn_Cursor INTO @DBname, @SCHname, @TBLname, @COLname, @COLdatatype;\r\n--\r\nWHILE @@FETCH_STATUS=0 BEGIN\r\n\tSET @SQLcmd --\r\n\t\t=N'INSERT INTO #SearchResults(DatabaseName, SchemaName, TableName, ColumnName, ColumnDataType, TableRowCount, StringOccuranceCount)'+CHAR(10) --\r\n\t\t +N'SELECT '''+@DBname+N''' AS \"DatabaseName\",'+CHAR(10) --\r\n\t\t +N'\t'''+@SCHname+N''' AS \"SchemaName\",'+CHAR(10) --\r\n\t\t +N'\t'''+@TBLname+N''' AS \"TableName\",'+CHAR(10) --\r\n\t\t +N'\t'''+@COLname+N''' AS \"ColumnName\",'+CHAR(10) --\r\n\t\t +N'\t'''+@COLdatatype+N''' AS \"ColumnDataType\",'+CHAR(10) --\r\n\t\t +N'\t(SELECT COUNT(1) FROM ['+@DBname+N'].['+@SCHname+N'].['+@TBLname+N'] WITH (NOLOCK)) AS \"TableRowCount\",'+CHAR(10) --\r\n\t\t +N'\tCOUNT(1) AS \"StringOccuranceCount\"'+CHAR(10) --\r\n\t\t +N'FROM ['+@DBname+N'].['+@SCHname+N'].['+@TBLname+N'] WITH (NOLOCK)'+CHAR(10) --\r\n\t\t +N'WHERE ['+@COLname+N'] LIKE ''%'+@SearchString+N'%'';'+CHAR(10) --\r\n\t\t +N'GO';\r\n\t--\r\n\tPRINT @SQLcmd;\r\n\t--\r\n\tFETCH NEXT FROM SearchTableColumn_Cursor INTO @DBname, @SCHname, @TBLname, @COLname, @COLdatatype;\r\nEND;\r\nCLOSE SearchTableColumn_Cursor;\r\nDEALLOCATE SearchTableColumn_Cursor;\r\n--$EndRegion: SearchTableColumn_Cursor\r\n--\r\nPRINT '--';\r\nPRINT --\r\nN'SELECT DatabaseName, SchemaName, TableName, ColumnName, ColumnDataType, TableRowCount, StringOccuranceCount,\r\n\t(''SELECT * FROM [''+DatabaseName+''].[''+SchemaName+''].[''+TableName+''] WHERE [''+ColumnName+''] LIKE ''''%'+@SearchString+'%'''';'') AS SearchQuery\r\nFROM #SearchResults\r\nWHERE StringOccuranceCount<>0;';",
"placeholders": [
{
"name": "StringToSearch",
"defaultValue": null
}
]
}
{
"id": "a63e3390-24a9-4b7b-9b41-599be2122b3b",
"prefix": "TDC_SetStatsOn",
"description": "Set Statistics Time, IO ON",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:26.0086854Z",
"permissions": [],
"body": "SET STATISTICS TIME, IO ON\r\n$CURSOR$"
}
{
"id": "bfb1f0b6-16c4-4f04-bcf9-3ad56e726c8f",
"prefix": "TDC_ShrinkLogFile",
"description": "Shrink Database Log File",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:26.0086854Z",
"permissions": [],
"body": "USE $DatabaseName$;\nGO \n\nALTER DATABASE $DatabaseName$ SET RECOVERY SIMPLE WITH NO_WAIT;\nCHECKPOINT;\n\nDBCC SHRINKFILE(N'$DatabaseName$_log', 0 , TRUNCATEONLY);\nCHECKPOINT;",
"placeholders": [
{
"name": "DatabaseName",
"defaultValue": ""
}
]
}
{
"id": "0facf83c-5523-4f34-a91d-3d2672c63468",
"prefix": "TDC_ssf_values",
"description": "Select * from values",
"status": "pendingShared",
"lastModified": "2023-01-13T16:19:53.1499733Z",
"permissions": [],
"body": "SELECT * FROM (VALUES \r\n\t ('bad64860-900e-4548-974c-508138e897c3')\r\n\t,('66289b96-9e7c-4a55-b1dd-601bceeb9da7')\r\n\t,('672fbddb-c33f-4797-ad74-870f928d7b49')\r\n\t,('6a9bc961-3868-4df5-a42a-0dad5a857834')\r\n) t (DocumentId)"
}
{
"id": "e4ab4494-6cc9-4ffb-b48f-8685cf8bd95c",
"prefix": "TDC_StartJob",
"description": "Start Job",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:26.0096853Z",
"permissions": [],
"body": "EXEC msdb.dbo.sp_start_job --\n @job_name = '$job_name$';\nGO",
"placeholders": [
{
"name": "job_name",
"defaultValue": ""
}
]
}
{
"id": "d1e387e8-34e2-4996-8cbf-f041116e9374",
"prefix": "TDC_TallyTable_BenGan",
"description": "generates an itzik ben gan tally table",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:26.0096853Z",
"permissions": [],
"body": "-- Tally table known as a \"Ben-Gan\" style Tally\r\nWITH lv0 AS (SELECT 0 g UNION ALL SELECT 0)\r\n ,lv1 AS (SELECT 0 g FROM lv0 a CROSS JOIN lv0 b) -- 4\r\n ,lv2 AS (SELECT 0 g FROM lv1 a CROSS JOIN lv1 b) -- 16\r\n ,lv3 AS (SELECT 0 g FROM lv2 a CROSS JOIN lv2 b) -- 256\r\n ,lv4 AS (SELECT 0 g FROM lv3 a CROSS JOIN lv3 b) -- 65,536\r\n ,lv5 AS (SELECT 0 g FROM lv4 a CROSS JOIN lv4 b) -- 4,294,967,296\r\n ,Tally (n) AS (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM lv5)\r\nSELECT TOP (5) n\r\nFROM Tally\r\nORDER BY n;"
}
{
"id": "764cc3b2-7d14-4607-bd13-7ef1f01eccd0",
"prefix": "TDC_TallyTable_CrossJoin",
"description": "SQL 2008 and higher, generates a tally table using cross joins",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:26.0096853Z",
"permissions": [],
"body": "WITH Tally (n) AS\r\n(\r\n -- 1000 rows\r\n SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL))\r\n FROM (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) a(n)\r\n CROSS JOIN (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) b(n)\r\n CROSS JOIN (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) c(n)\r\n)\r\nSELECT *\r\nFROM Tally;"
}
{
"id": "42fc96e7-805f-4a09-86ac-eb1ce8e6e561",
"prefix": "TDC_TimeSpan",
"description": "Get a timespan between two dates",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:26.0096853Z",
"permissions": [],
"body": "DECLARE @sd DATETIME2(7) = '2021-08-25 12:16:16.6969221',\r\n\t@ed DATETIME2(7) = '2021-08-26 15:40:52.4579221'\r\n\r\n\r\nDECLARE @diff DECIMAL(19, 7) = DATEDIFF(MILLISECOND, @sd, @ed) \r\n\r\n\r\nSELECT CONCAT (\r\n\tCAST(@diff / (1000 * 60 * 60 * 24) AS INT), --days\r\n\t'.',\r\n\tRIGHT('0' + RTRIM(CAST((@diff / (1000 * 60 * 60)) % 24 AS INT)), 2) ,\t-- hours\r\n\t':',\t\r\n\tRIGHT('0' + RTRIM(CAST((@diff / (1000 * 60)) % 60 AS INT)), 2) ,\t\t-- minutes\r\n\t':',\r\n\tRIGHT('0' + RTRIM(CAST((@diff / 1000) % 60 AS INT)), 2) ,\t\t\t\t-- seconds\r\n\t'.',\r\n\tPARSENAME(@diff % 1000, 2) \t\t\t\t\t\t\t\t\t\t\t\t-- milliseconds\r\n)"
}
{
"id": "1bb4b796-1e0f-47a1-b6ab-ff2f5999dcd8",
"prefix": "TDC_timings",
"description": "Wraps a simple timings test harness around the selected code",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:26.0106853Z",
"permissions": [],
"body": "/**\nBased on code by Phil Factor (https://www.red-gate.com/hub/product-learning/sql-prompt/record-t-sql-execution-times-using-sql-prompt-snippet).\n**/\nDECLARE @log table\n(\n TheOrder int IDENTITY(1, 1),\n WhatHappened varchar(200),\n WhenItDid datetime2 DEFAULT GETDATE()\n)\n----start of timing\nINSERT INTO @log(WhatHappened)\nSELECT 'Starting $routine$' --place at the start\n \n$SELECTEDTEXT$$CURSOR$\n \n--where the routine you want to time ends\nINSERT INTO @log(WhatHappened)\nSELECT '$routine$ took '\nSELECT ending.WhatHappened, DATEDIFF(ms, starting.WhenItDid, ending.WhenItDid)\nFROM @log starting\n INNER JOIN @log ending\n ON ending.TheOrder = starting.TheOrder + 1\n--list out all the timings",
"placeholders": [
{
"name": "routine",
"defaultValue": ""
}
]
}
{
"id": "3d778519-0b50-4562-ac76-071e6cd5867e",
"prefix": "TDC_TransferLogins",
"description": "Transfer Logins with Passwords between Instances of SQL Server",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:26.0106853Z",
"permissions": [],
"body": "/* =========================================================================================================================================\r\n-- Server\t\t: Execute as is in OLD Server >> Copy Generated Code to NEW Server and Execute\r\n-- Database\t\t: master\r\n-- Script\t\t: TransferLogins\r\n-- Description\t: Transfer Logins with Passwords between Instances of SQL Server\r\n-- Usage\t\t: Execute the Script in OLD Server and then Copy the Code Generated to NEW Server and Execute.\r\n-- Link\t\t\t: https://docs.microsoft.com/en-us/troubleshoot/sql/security/transfer-logins-passwords-between-instances\r\n========================================================================================================================================= */\r\nUSE master;\r\nGO\r\n\r\nSET NOCOUNT ON;\r\n\r\n--\r\nIF OBJECT_ID('sp_hexadecimal') IS NOT NULL\r\n\tDROP PROCEDURE dbo.sp_hexadecimal;\r\nGO\r\n\r\nCREATE PROCEDURE dbo.sp_hexadecimal\r\n(\r\n\t@binvalue VARBINARY(256),\r\n\t@hexvalue VARCHAR(514) OUTPUT\r\n)\r\nAS\r\nBEGIN\r\n\tDECLARE @charvalue VARCHAR(514);\r\n\tDECLARE @i INT;\r\n\tDECLARE @length INT;\r\n\tDECLARE @hexstring CHAR(16);\r\n\r\n\tSELECT @charvalue = '0x';\r\n\tSELECT @i = 1;\r\n\tSELECT @length = DATALENGTH(@binvalue);\r\n\tSELECT @hexstring = '0123456789ABCDEF';\r\n\r\n\tWHILE (@i <= @length)\r\n\t\tBEGIN\r\n\t\t\tDECLARE @tempint INT;\r\n\t\t\tDECLARE @firstint INT;\r\n\t\t\tDECLARE @secondint INT;\r\n\r\n\t\t\tSELECT @tempint = CONVERT(INT, SUBSTRING(@binvalue, @i, 1));\r\n\t\t\tSELECT @firstint = FLOOR(@tempint / 16);\r\n\t\t\tSELECT @secondint = @tempint - (@firstint * 16);\r\n\t\t\tSELECT @charvalue = @charvalue + SUBSTRING(@hexstring, @firstint + 1, 1) + SUBSTRING(@hexstring, @secondint + 1, 1);\r\n\r\n\t\t\tSELECT @i = @i + 1;\r\n\t\tEND;\r\n\r\n\tSELECT @hexvalue = @charvalue;\r\nEND;\r\nGO\r\n\r\n--\r\nIF OBJECT_ID('sp_help_revlogin') IS NOT NULL\r\n\tDROP PROCEDURE dbo.sp_help_revlogin;\r\nGO\r\n\r\nCREATE PROCEDURE dbo.sp_help_revlogin\r\n(\r\n\t@login_name sysname = NULL\r\n)\r\nAS\r\nBEGIN\r\n\tDECLARE @name sysname;\r\n\tDECLARE @type VARCHAR(1);\r\n\tDECLARE @hasaccess INT;\r\n\tDECLARE @denylogin INT;\r\n\tDECLARE @is_disabled INT;\r\n\tDECLARE @PWD_varbinary VARBINARY(256);\r\n\tDECLARE @PWD_string VARCHAR(514);\r\n\tDECLARE @SID_varbinary VARBINARY(85);\r\n\tDECLARE @SID_string VARCHAR(514);\r\n\tDECLARE @tmpstr VARCHAR(1024);\r\n\tDECLARE @is_policy_checked VARCHAR(3);\r\n\tDECLARE @is_expiration_checked VARCHAR(3);\r\n\tDECLARE @Prefix VARCHAR(255);\r\n\tDECLARE @defaultdb sysname;\r\n\tDECLARE @defaultlanguage sysname;\r\n\tDECLARE @tmpstrRole VARCHAR(1024);\r\n\r\n\tIF (@login_name IS NULL)\r\n\t\tDECLARE login_curs CURSOR FOR\r\n\t\tSELECT p.sid, p.name, p.type, p.is_disabled, p.default_database_name, l.hasaccess, l.denylogin, p.default_language_name\r\n\t\tFROM sys.server_principals AS p\r\n\t\tLEFT JOIN sys.syslogins AS l ON (l.name = p.name)\r\n\t\tWHERE p.type IN ( 'S', 'G', 'U' ) AND p.name <> 'sa'\r\n\t\tORDER BY p.name;\r\n\tELSE\r\n\t\tDECLARE login_curs CURSOR FOR\r\n\t\tSELECT p.sid, p.name, p.type, p.is_disabled, p.default_database_name, l.hasaccess, l.denylogin, p.default_language_name\r\n\t\tFROM sys.server_principals AS p\r\n\t\tLEFT JOIN sys.syslogins AS l ON (l.name = p.name)\r\n\t\tWHERE p.type IN ( 'S', 'G', 'U' ) AND p.name = @login_name\r\n\t\tORDER BY p.name;\r\n\r\n\tOPEN login_curs;\r\n\r\n\tFETCH NEXT FROM login_curs\r\n\tINTO @SID_varbinary, @name, @type, @is_disabled, @defaultdb, @hasaccess, @denylogin, @defaultlanguage;\r\n\r\n\tIF (@@fetch_status = -1)\r\n\tBEGIN\r\n\t\tPRINT 'No login(s) found.';\r\n\t\tCLOSE login_curs;\r\n\t\tDEALLOCATE login_curs;\r\n\t\tRETURN -1;\r\n\tEND;\r\n\r\n\tPRINT '/* sp_help_revlogin script */';\r\n\tPRINT '/** Generated ' + CONVERT(VARCHAR(32), GETDATE()) + ' on ' + @@SERVERNAME + ' **/';\r\n\tPRINT '';\r\n\r\n\tWHILE (@@fetch_status <> -1)\r\n\tBEGIN\r\n\t\tIF (@@fetch_status <> -2)\r\n\t\tBEGIN\r\n\t\t\tPRINT '';\r\n\t\t\tPRINT '-- Login: ' + @name;\r\n\t\t\tPRINT 'IF NOT EXISTS (SELECT * FROM sys.server_principals WHERE name = N''' + @name + ''')';\r\n\t\t\tPRINT 'BEGIN';\r\n\r\n\t\t\tIF (@type IN ( 'G', 'U' ))\r\n\t\t\t\tBEGIN -- NT authenticated account/group \r\n\t\t\t\t\tSET @tmpstr = '\tCREATE LOGIN ' + QUOTENAME(@name) + ' FROM WINDOWS WITH DEFAULT_DATABASE = [' + @defaultdb + ']';\r\n\t\t\t\tEND;\r\n\t\t\tELSE\r\n\t\t\t\tBEGIN -- SQL Server authentication\r\n\t\t\t\t\t-- obtain password and sid\r\n\t\t\t\t\tSET @PWD_varbinary = CAST(LOGINPROPERTY(@name, 'PasswordHash') AS VARBINARY(256));\r\n\r\n\t\t\t\t\tEXEC dbo.sp_hexadecimal @binvalue = @PWD_varbinary, @hexvalue = @PWD_string OUT;\r\n\t\t\t\t\tEXEC dbo.sp_hexadecimal @binvalue = @SID_varbinary, @hexvalue = @SID_string OUT;\r\n\r\n\t\t\t\t\t-- obtain password policy state\r\n\t\t\t\t\tSELECT @is_policy_checked = CASE is_policy_checked WHEN 1 THEN 'ON' WHEN 0 THEN 'OFF' ELSE NULL END\r\n\t\t\t\t\tFROM sys.sql_logins\r\n\t\t\t\t\tWHERE name = @name;\r\n\r\n\t\t\t\t\tSELECT @is_expiration_checked = CASE is_expiration_checked WHEN 1 THEN 'ON' WHEN 0 THEN 'OFF' ELSE NULL END\r\n\t\t\t\t\tFROM sys.sql_logins\r\n\t\t\t\t\tWHERE name = @name;\r\n\r\n\t\t\t\t\tSET @tmpstr = '\tCREATE LOGIN ' + QUOTENAME(@name) + ' WITH PASSWORD = ' + @PWD_string + ' HASHED, SID = ' + @SID_string + ', DEFAULT_DATABASE = [' + @defaultdb + ']' + ', DEFAULT_LANGUAGE = [' + @defaultlanguage + ']';\r\n\r\n\t\t\t\t\tIF (@is_policy_checked IS NOT NULL)\r\n\t\t\t\t\t\tBEGIN\r\n\t\t\t\t\t\t\tSET @tmpstr = @tmpstr + ', CHECK_POLICY = ' + @is_policy_checked;\r\n\t\t\t\t\t\tEND;\r\n\r\n\t\t\t\t\tIF (@is_expiration_checked IS NOT NULL)\r\n\t\t\t\t\t\tBEGIN\r\n\t\t\t\t\t\t\tSET @tmpstr = @tmpstr + ', CHECK_EXPIRATION = ' + @is_expiration_checked;\r\n\t\t\t\t\t\tEND;\r\n\t\t\t\tEND;\r\n\r\n\t\t\tIF (@denylogin = 1)\r\n\t\t\t\tBEGIN -- login is denied access\r\n\t\t\t\t\tSET @tmpstr = @tmpstr + '; DENY CONNECT SQL TO ' + QUOTENAME(@name);\r\n\t\t\t\tEND;\r\n\t\t\tELSE IF (@hasaccess = 0)\r\n\t\t\t\tBEGIN -- login exists but does not have access\r\n\t\t\t\t\tSET @tmpstr = @tmpstr + '; REVOKE CONNECT SQL TO ' + QUOTENAME(@name);\r\n\t\t\t\tEND;\r\n\r\n\t\t\tIF (@is_disabled = 1)\r\n\t\t\t\tBEGIN -- login is disabled\r\n\t\t\t\t\tSET @tmpstr = @tmpstr + '; ALTER LOGIN ' + QUOTENAME(@name) + ' DISABLE';\r\n\t\t\t\tEND;\r\n\r\n\t\t\tSET @Prefix = '\tEXEC master.dbo.sp_addsrvrolemember @loginame=''';\r\n\t\t\tSET @tmpstrRole = '';\r\n\r\n\t\t\tSELECT @tmpstrRole = @tmpstrRole\r\n\t\t\t\t\t\t\t\t\t+ CASE WHEN L.sysadmin = 1 THEN @Prefix + L.LoginName + ''', @rolename=''sysadmin''' ELSE '' END\r\n\t\t\t\t\t\t\t\t\t\t+ CASE WHEN L.securityadmin = 1 THEN @Prefix + L.LoginName + ''', @rolename=''securityadmin''' ELSE '' END\r\n\t\t\t\t\t\t\t\t\t\t\t+ CASE WHEN L.serveradmin = 1 THEN @Prefix + L.LoginName + ''', @rolename=''serveradmin''' ELSE '' END\r\n\t\t\t\t\t\t\t\t\t\t\t\t+ CASE WHEN L.setupadmin = 1 THEN @Prefix + L.LoginName + ''', @rolename=''setupadmin''' ELSE '' END\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t+ CASE WHEN L.processadmin = 1 THEN @Prefix + L.LoginName + ''', @rolename=''processadmin''' ELSE '' END\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ CASE WHEN L.diskadmin = 1 THEN @Prefix + L.LoginName + ''', @rolename=''diskadmin''' ELSE '' END\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ CASE WHEN L.dbcreator = 1 THEN @Prefix + L.LoginName + ''', @rolename=''dbcreator''' ELSE '' END\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ CASE WHEN L.bulkadmin = 1 THEN @Prefix + L.LoginName + ''', @rolename=''bulkadmin''' ELSE '' END\r\n\t\t\tFROM (\r\n\t\t\t\t\tSELECT CONVERT(VARCHAR(100), SUSER_SNAME(sid)) AS \"LoginName\", sysadmin, securityadmin, serveradmin, setupadmin, processadmin, diskadmin, dbcreator, bulkadmin\r\n\t\t\t\t\tFROM sys.syslogins\r\n\t\t\t\t\tWHERE (sysadmin <> 0 OR securityadmin <> 0 OR serveradmin <> 0 OR setupadmin <> 0 OR processadmin <> 0 OR diskadmin <> 0 OR dbcreator <> 0 OR bulkadmin <> 0)\r\n\t\t\t\t\t\tAND name = @name\r\n\t\t\t\t ) AS L;\r\n\r\n\t\t\tPRINT @tmpstr;\r\n\t\t\tPRINT @tmpstrRole;\r\n\t\t\tPRINT 'END';\r\n\t\tEND;\r\n\r\n\t\tFETCH NEXT FROM login_curs\r\n\t\tINTO @SID_varbinary, @name, @type, @is_disabled, @defaultdb, @hasaccess, @denylogin, @defaultlanguage;\r\n\tEND;\r\n\r\n\tCLOSE login_curs;\r\n\tDEALLOCATE login_curs;\r\n\r\n\tRETURN 0;\r\nEND;\r\nGO\r\n\r\n--\r\nEXEC dbo.sp_help_revlogin @login_name = NULL;"
}
{
"id": "2f16ef90-2025-4861-b830-8691215b2497",
"prefix": "TDC_TryCatch",
"description": "TRY ... CATCH fragment",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:26.0106853Z",
"permissions": [],
"body": "BEGIN TRY\n $SELECTEDTEXT$\nEND TRY\nBEGIN CATCH\n\t;THROW\nEND CATCH;"
}
{
"id": "4211d096-4e16-42dc-b23c-21aa1f989c9b",
"prefix": "TDC_WhoIsActiveExtended",
"description": "WhoIsActive Extended",
"status": "pendingShared",
"lastModified": "2022-11-17T16:08:26.0106853Z",
"permissions": [],
"body": "EXEC master.dbo.sp_WhoIsActive --\n @get_outer_command = 1,\n @get_plans = 1,\n @get_transaction_info = 1,\n @get_additional_info = 1;"
}
@matthew-n
Copy link
Author

forking for reference

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment