Skip to content

Instantly share code, notes, and snippets.

View tcartwright's full-sized avatar

Tim Cartwright tcartwright

  • Houston, Texas
View GitHub Profile
@tcartwright
tcartwright / sp_ArchiveTableData.sql
Last active December 5, 2025 19:55
SQL SERVER: Archive table data stored procedure
/* EXEC sp_helptext 'dbo.sp_ArchiveTableData' */
USE [master]
GO
/*
Author: Tim Cartwright
Purpose:
Archives large tables using a "nibbling delete" pattern - moving data in small batches
@tcartwright
tcartwright / CheckLockEscalations.sql
Last active December 4, 2025 22:03
SQL SERVER: Get lock escalations
-- Check for lock escalation issues
SELECT
'lock escalation' AS [result_name],
OBJECT_NAME(p.object_id, db_id()) AS TableName,
p.index_id,
i.name AS IndexName,
SUM(CASE WHEN l.resource_type = 'EXTENT' THEN 1 ELSE 0 END) AS ExtentLocks,
SUM(CASE WHEN l.resource_type = 'PAGE' THEN 1 ELSE 0 END) AS PageLocks,
SUM(CASE WHEN l.resource_type = 'KEY' THEN 1 ELSE 0 END) AS KeyLocks,
SUM(CASE WHEN l.resource_type = 'OBJECT' THEN 1 ELSE 0 END) AS TableLocks,
@tcartwright
tcartwright / CaptureLockEscalations.sql
Created November 14, 2025 15:08
SQL SERVER: Capture lock escalations for a server
-- sourced from claude.ai
-- Create Extended Event session to capture lock escalations
CREATE EVENT SESSION [CaptureEscalations] ON SERVER
ADD EVENT sqlserver.lock_escalation(
ACTION(
sqlserver.client_app_name,
sqlserver.client_hostname,
sqlserver.database_name,
sqlserver.query_hash,
@tcartwright
tcartwright / CalculateNibblingDeletesBatchSize.sql
Created November 13, 2025 19:17
SQL SERVER: Calculate optimum batch size for nibbling deletes based on rows per page
-- Calculate optimal batch size based on actual rows per page
DECLARE @RowsPerPage INT
DECLARE @MaxLocks INT = 4000 -- 80% of 5000 threshold
DECLARE @OptimalBatchSize INT
-- Get rows per page
SELECT @RowsPerPage =
CASE
WHEN SUM(used_page_count) > 0
THEN SUM(row_count) / SUM(used_page_count)
@tcartwright
tcartwright / CreateAppRoles.sql
Last active October 30, 2025 14:43
SQL SERVER: Create AppUser and AppUserReadOnly roles, and map logins to roles
DECLARE @DatabaseName NVARCHAR(128)
DECLARE @SQL NVARCHAR(MAX)
DECLARE db_cursor CURSOR FOR
SELECT name
FROM sys.databases
WHERE database_id > 4 -- Excludes system databases (master, tempdb, model, msdb)
AND state_desc = 'ONLINE'
AND [name] NOT IN ('DBATools')
AND is_read_only = 0
@tcartwright
tcartwright / GetTableDataDistribution.sql
Last active October 23, 2025 13:29
SQL SERVER: Get tables data distribution for help with index creation
DECLARE @table SYSNAME = '[dbo].[TableName]';
DECLARE @sql NVARCHAR(MAX) = N'';
DECLARE @RowCount BIGINT;
-- Get total row count once (no need to scan per column)
SELECT @RowCount = SUM(p.[rows])
FROM sys.partitions AS p
WHERE p.[object_id] = OBJECT_ID(@table)
AND p.[index_id] IN (0, 1); -- heap or clustered index
@tcartwright
tcartwright / IndexColumnAnalysis.sql
Last active October 22, 2025 14:10
SQL SERVER: Index column analysis
/*
-- Brent Ozars script:
EXEC dbo.sp_BlitzIndex @SchemaName='dbo', @TableName='TableName', @fullOutput = 1
*/
-- makes it very easy to spot possible duplicates that can be combined.
SELECT
[i].[name] AS IndexName,
[i].[type_desc] AS IndexType,
STUFF(
@tcartwright
tcartwright / ResetChanges.cmd
Created October 16, 2025 18:59
CMD: Git undo changes to a file when git or visual studio wont let you
git rm .gitattributes # Removes the .gitattributes file from both the working directory and the Git index (staging area).
git add -A # Stages all changes: added files, modified files, and deletions (like the .gitattributes removal) for the next commit.
git reset --hard # Resets the working directory and index to the last committed state — all staged and unstaged changes are lost.
@tcartwright
tcartwright / TestSQLServerConnectivity.ps1
Last active August 28, 2025 13:16
SQL SERVER: Test connectivity to server from sql server
EXEC sp_configure 'show advanced options', 1;
RECONFIGURE;
EXEC sp_configure 'xp_cmdshell', 1;
RECONFIGURE;
/************************************************************
** Change the value of the @server variable here
*************************************************************/
DECLARE @Server VARCHAR(255) = 'servername'
@tcartwright
tcartwright / GenerateCert.ps1
Created August 25, 2025 16:05
POWERSHELL: Generate a cert
# IMPORTANT: !!Generated certs should NOT be used in production!!
$cert = New-SelfSignedCertificate `
-Subject "CN=sso.servername.it" `
-KeyAlgorithm RSA `
-KeyLength 2048 `
-CertStoreLocation "Cert:\CurrentUser\My" `
-NotAfter (Get-Date).AddYears(5) `
-KeyExportPolicy Exportable `
-Type Custom `
-TextExtension @("2.5.29.37={text}1.3.6.1.5.5.7.3.3") # Code signing usage