Skip to content

Instantly share code, notes, and snippets.

View kevinmartintech's full-sized avatar

Kevin Martin kevinmartintech

View GitHub Profile
@kevinmartintech
kevinmartintech / FindSp_WhoIsActiveBlockingLocking.sql
Created September 10, 2025 14:56
sp_WhoIsActive with blocking and locking check
--DECLARE @schema varchar(MAX);
EXEC master.dbo.sp_WhoIsActive @get_locks = 1, @find_block_leaders = 1, @get_plans = 1, @output_column_list = '
[dd hh:mm:ss.mss][sql_text][query_plan][locks][blocking_session_id][blocked_session_count][wait_info]
[CPU][used_memory][reads][writes][physical_reads]
[status][open_tran_count][percent_complete]
[host_name]
[database_name]
@kevinmartintech
kevinmartintech / FindTableCountRowDifference.sql
Created September 10, 2025 14:54
Script to monitor table counts. Good for when tuning batch looping DELETES, UPDATES scripts. Count the row differences every minute.
DECLARE @StartTime datetime = GETDATE();
DECLARE @LastMinuteStart datetime = DATEADD(MINUTE, -1, @StartTime);
DECLARE @CurrentMinuteStart datetime;
DECLARE @CurrentMinuteStartMessage nvarchar(30);
DECLARE @LastRowCount bigint = -1;
WHILE 1 = 1
BEGIN
SET @CurrentMinuteStart = DATEADD(MINUTE, DATEDIFF(MINUTE, @StartTime, GETDATE()), @StartTime);
@kevinmartintech
kevinmartintech / FindAgentJobHistoryInfo.sql
Last active August 14, 2025 15:50
This script finds agent job history and agent job info. Use it instead of the Job History / Log File Viewer
DECLARE @JobName sysname = '[SQL-SERVER-AGENT-JOB-NAME]'; /* Enter the job name you want to view the job history for */
DECLARE @DaysBack int = 5; /* Change this value as needed */
DECLARE @ShowOnlyJobSummary bit = 1; /* Set to 1 for just the summary, or 0 for all job steps */
DECLARE @ShowJobInformation bit = 0; /* Set to 1 to view the job information. You can also view this in SSMS under SQL Server Agent -> Jobs */
/**********************************************************************************************************************
** Job History
**********************************************************************************************************************/
SET NOCOUNT ON;
@kevinmartintech
kevinmartintech / SQL Server Database and Object ANSI Settings Check.sql
Last active August 18, 2025 20:59
SQL Server Database and Object ANSI Settings Check - Validates that database-level ANSI settings, object-level metadata (ANSI_NULLS, QUOTED_IDENTIFIER), DDL SET options, and column-level ANSI_PADDING are correctly configured to ensure compatibility with indexed views, filtered indexes, persisted computed columns, and standards-based T-SQL behavior.
/**********************************************************************************************************************
** Name: SQL Server Database and Object ANSI Settings Check
** Description: Validates that database-level ANSI settings, object-level metadata (ANSI_NULLS, QUOTED_IDENTIFIER),
** DDL SET options, and column-level ANSI_PADDING are correctly configured to ensure compatibility with
** indexed views, filtered indexes, persisted computed columns, and standards-based T-SQL behavior.
**
** NOTE: MANUAL CHECK REQUIRED FOR TABLES
** Tables do not store ANSI_NULLS or QUOTED_IDENTIFIER settings in metadata. These settings are
** session-level at creation and cannot be altered later.
** To check:
@kevinmartintech
kevinmartintech / Nullable Columns with No Non-Null Rows Check
Created April 9, 2025 18:06
Use to find nullable columns with no non-null rows.
/**********************************************************************************************************************
** Nullable Columns with No Non-Null Rows Check
** Use to find nullable columns with no non-null rows.
** For more information see: https://www.spdevelop.org/best-practices-and-findings/table-conventions#150
** Can be intensive if no supporting indexes, so run outside of work hours.
**********************************************************************************************************************/
DECLARE @SchemaName sysname = NULL; /* Set to NULL to process all schemas. */
DECLARE @TableName sysname = NULL; /* Set to NULL to process all tables. */
/* End configurable variables */
@kevinmartintech
kevinmartintech / FindLongestDataLength
Created April 8, 2025 19:25
This script help find the longest data value in each of the text columns. Helpful for creating ETL tables.
DECLARE @TableName sysname = '<SchemaName, , dbo>.<TableName, , MyTable>';
SET NOCOUNT ON;
DECLARE
@column_id varchar(36)
,@StringToExecute nvarchar(MAX);
DROP TABLE IF EXISTS #Receiver;
CREATE TABLE #Receiver (LongestDataLength int NULL);
@kevinmartintech
kevinmartintech / FindExportTableSampleData.ps1
Created March 11, 2025 22:39
PowerShell Export Table Sample Data
Remove-Module SqlServer
Import-Module SqlServer -RequiredVersion 22.3.0 -Force
$ServerInstance = "SQLServerName"
$Database = "DatabaseName"
$Path = "C:\Export\"
$TableListQuery = "SELECT
SchemaTableName = S.name + '.' + T.name
,SchemaTableNameCleaned = REPLACE(S.name, '\', '') + '.' + REPLACE(T.name, '\', '')
FROM
SET NOCOUNT ON;
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
WITH TableInformation
AS (
SELECT
object_id = T.object_id
,[Schema Name] = S.name
,[Table Name] = T.name
,[Table Description] = CONVERT(nvarchar(MAX), EP.value)
FROM
/*************************************************************************************************
** # Database User and Roles Assignment Script
**
** If your application uses only one database, a contained user should be created (RECOMMENDED)
** You can create a contained user in each database with the same username and password
** If your application uses multiple databases, you CAN create a SQL Server login (NOT RECOMMENDED)
** You will create a database user from the SQL Server login for each database
** THIS IS NOT PORTABLE! SQL LOGIN MUST BE CREATED ON OTHER SQL SERVERS WITH THE SAME SID.
**
** This script will enabled contained users if it is executed on a SQL Server
@kevinmartintech
kevinmartintech / tvc.sql
Created February 8, 2023 19:55
Automatically create a table variable (or temp table) in which to store the results of (for example) executing a stored procedure, function or query
/**
Summary: >
This is a temporary batch for creating such things as table variables,
temporary tables or anything else that needs a column list
Author: Phil Factor
Based on code from https://www.red-gate.com/hub/product-learning/sql-prompt/building-reusable-table-build-scripts-using-sql-prompt
**/
Declare @TheExpression NVARCHAR(MAX)=
N'$SELECTEDTEXT$'