├── AlwaysOn ├── AlwaysOn_CheckStatus.sql ├── AlwaysOn_DBSynchroETA.sql ├── AlwaysOn_FailoverHistory.sql ├── AlwaysOn_ForceManualFailover.sql └── AlwaysOn_sp_help_revlogin.sql ├── Backups ├── SQLBackups_BackupAllDBsToDisk.sql ├── SQLBackups_BackupEstimations.sql ├── SQLBackups_BackupsChain.sql ├── SQLBackups_BackupsDone.sql ├── SQLBackups_LatestDBBackups.sql ├── SQLBackups_Progress.sql ├── SQLBackups_RestoresDone.sql └── TDP │ └── Backups_TDP_CheckBackups.ps1 ├── Collations └── Collations_CollationChange.cmd ├── Connectivity ├── Connectivity_CheckKerberos.sql └── Connectivity_CheckSPNs.cmd ├── DBStatus ├── DB_RepairADBInSuspectState.sql ├── SQLInstance_RecoverAllDBsInSuspectState.sql └── SQLInstance_RecoverAllDBsInSuspectState2.sql ├── Databases ├── Databases_CheckShrinkProgress.sql ├── Databases_CheckVlogsForShrink.sql ├── Databases_DatafileSplitProgressCheck.sql ├── Databases_FindATableInAllDBs.sql ├── Databases_GetFileSizes.sql ├── Databases_GetTablesSize.sql ├── Databases_RenameDB.sql └── Databases_ShrinkDatafile.sql ├── Deadlocks ├── Deadlocks_CheckDeadlockNumber.sql └── Deadlocks_CheckDeadlocks.sql ├── Files ├── DropTempdbDatafile.sql └── ReallocateDBFiles.sql ├── Indexes ├── Indexes_BiggestIndexesInDB.sql ├── Indexes_EnableAllIndexesInADB.sql ├── Indexes_FindDisabledIndexes.sql ├── Indexes_IndexFragmentation.sql ├── Indexes_IndexesUsageInDB.sql └── Indexes_PotentiallyRedundantIndexesInDB.sql ├── Infrastructure ├── Infrasctructure_CheckConnectivity.ps1 ├── Infrastructure_CheckWindowsLicenseStatus.ps1 ├── Wintel_CheckIPs.ps1 ├── Wintel_CheckMountpoints.ps1 ├── Wintel_Drives_CheckBytesPerCluster.ps1 ├── Wintel_Drives_DriveSizes.ps1 ├── Wintel_GetLast10ServerReboots.ps1 └── Wintel_GetListApplications.ps1 ├── Memory └── Memory_ReleaseSQLMemoryInUse.sql ├── Migrations ├── FixOrphans.sql └── Migrations_CompareDBs.sql ├── Partitioning └── Partitioning_ListPartitions.sql ├── Performance ├── Performance_ActiveTransactions.sql ├── Performance_BlockedProcesses.sql ├── Performance_BufferPoll.sql ├── Performance_CachePlans.sql ├── Performance_CurrentMemoryUsageByDB.sql ├── Performance_Emulation_sp_who2.sql └── Performance_FindLargeTransactions.sql ├── Processes ├── SQLProcesses_ActiveProcesses+QueryPlan.sql ├── SQLProcesses_ActiveProcesses.sql ├── SQLProcesses_BadSessions.sql ├── SQLProcesses_KillAllDBProcesses.sql ├── SQLProcesses_MostCPUbyHandle.sql ├── SQLProcesses_ProgramStatistics.sql └── SQLProcesses_SQLPercentage.sql ├── QEP_AlreadyRunningProcesses.sql ├── QEP_EstimatedExecutionPlans.sql ├── Queries_Top10HeavyQueries.sql ├── README.md ├── Replications └── Replications_Status.sql ├── SPs └── SPs_RecompileSP.sql ├── SQLJobs ├── SQLJobs_CheckJobHistory.sql ├── SQLJobs_CheckSQLJobsRunning.sql └── SQLJobs_EnableAgentXPs.sql ├── SSIS └── SSIS_WhichJobExecutedaPackage.sql ├── Snippets ├── Snippet_CursorSnippet.sql └── Snippet_SQLDateTimeSnippets.sql ├── Statistics ├── Databases_CPU_IO_Statistics.sql └── Databases_RAM_Statistics.sql ├── Testing └── Testing_ScriptToGrowDB.sql └── Users ├── Users_AuditConnections.sql ├── Users_AuditUsersLists.sql ├── Users_CheckObjectsOwnership.sql ├── Users_CreateDB_ExecutorDBRole.sql ├── Users_CreateRoleDBExecutor.sql ├── Users_DropDBLogins.sql ├── Users_ExportLogin.sql ├── Users_SearchForALogin.sql ├── Users_UserPermissionsInDB.sql └── Users_WhoCreatedAUser.sql /AlwaysOn/AlwaysOn_CheckStatus.sql: -------------------------------------------------------------------------------- 1 | --File: AlwaysOn\AlwaysOn_CheckStatus.sql 2 | --Extracted from https://sqlperformance.com/2015/08/monitoring/availability-group-replica-sync 3 | --Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 4 | --Added in 2020-02-27 5 | 6 | -- This script will check AlwaysOn status 7 | 8 | SELECT 9 | ar.replica_server_name, 10 | adc.database_name, 11 | ag.name AS ag_name, 12 | drs.is_local, 13 | CASE WHEN hags.primary_replica = ar.replica_server_name THEN 1 ELSE 0 END AS is_primary_replica, 14 | drs.synchronization_state_desc, 15 | drs.is_commit_participant, 16 | drs.synchronization_health_desc, 17 | drs.recovery_lsn, 18 | drs.truncation_lsn, 19 | drs.last_sent_lsn, 20 | drs.last_sent_time, 21 | drs.last_received_lsn, 22 | drs.last_received_time, 23 | drs.last_hardened_lsn, 24 | drs.last_hardened_time, 25 | drs.last_redone_lsn, 26 | drs.last_redone_time, 27 | drs.log_send_queue_size, 28 | drs.log_send_rate, 29 | drs.redo_queue_size, 30 | drs.redo_rate, 31 | drs.filestream_send_rate, 32 | drs.end_of_log_lsn, 33 | drs.last_commit_lsn, 34 | drs.last_commit_time 35 | FROM sys.dm_hadr_database_replica_states AS drs 36 | INNER JOIN sys.availability_databases_cluster AS adc ON drs.group_id = adc.group_id AND drs.group_database_id = adc.group_database_id 37 | INNER JOIN sys.availability_groups AS ag ON ag.group_id = drs.group_id 38 | INNER JOIN sys.availability_replicas AS ar ON drs.group_id = ar.group_id AND drs.replica_id = ar.replica_id 39 | INNER JOIN sys.dm_hadr_availability_group_states AS hags ON hags.group_id = ag.group_id 40 | ORDER BY ag.name, ar.replica_server_name, adc.database_name; -------------------------------------------------------------------------------- /AlwaysOn/AlwaysOn_DBSynchroETA.sql: -------------------------------------------------------------------------------- 1 | --File: AlwaysOn\AlwaysOn_DBSynchroETA.sql 2 | --Extracted from https://www.sqlshack.com/measuring-availability-group-synchronization-lag/ 3 | --Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 4 | --Added in 2021-11-30 5 | 6 | ;WITH 7 | AG_Stats AS 8 | ( 9 | SELECT AR.replica_server_name, 10 | HARS.role_desc, 11 | Db_name(DRS.database_id) [DBName], 12 | DRS.last_commit_time 13 | FROM sys.dm_hadr_database_replica_states DRS 14 | INNER JOIN sys.availability_replicas AR ON DRS.replica_id = AR.replica_id 15 | INNER JOIN sys.dm_hadr_availability_replica_states HARS ON AR.group_id = HARS.group_id 16 | AND AR.replica_id = HARS.replica_id 17 | ), 18 | Pri_CommitTime AS 19 | ( 20 | SELECT replica_server_name 21 | , DBName 22 | , last_commit_time 23 | FROM AG_Stats 24 | WHERE role_desc = 'PRIMARY' 25 | ), 26 | Sec_CommitTime AS 27 | ( 28 | SELECT replica_server_name 29 | , DBName 30 | , last_commit_time 31 | FROM AG_Stats 32 | WHERE role_desc = 'SECONDARY' 33 | ) 34 | SELECT p.replica_server_name [primary_replica] 35 | , p.[DBName] AS [DatabaseName] 36 | , s.replica_server_name [secondary_replica] 37 | , DATEDIFF(ss,s.last_commit_time,p.last_commit_time) AS [Sync_Lag_Secs] 38 | FROM Pri_CommitTime p 39 | LEFT JOIN Sec_CommitTime s ON [s].[DBName] = [p].[DBName] -------------------------------------------------------------------------------- /AlwaysOn/AlwaysOn_FailoverHistory.sql: -------------------------------------------------------------------------------- 1 | --File: AlwaysOn\AlwaysOn_FailoverHitory.sql 2 | --Extracted from https://dba.stackexchange.com/questions/76016/how-to-check-history-of-primary-node-in-an-availability-group 3 | --Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 4 | --Added in 2022-03-14 5 | 6 | declare @xel_path varchar(1024); 7 | declare @utc_adjustment int = datediff(hour, getutcdate(), getdate()); 8 | 9 | ------------------------------------------------------------------------------- 10 | ------------------- target event_file path retrieval -------------------------- 11 | ------------------------------------------------------------------------------- 12 | ;with target_data_cte as 13 | ( 14 | select 15 | target_data = 16 | convert(xml, target_data) 17 | from sys.dm_xe_sessions s 18 | inner join sys.dm_xe_session_targets st 19 | on s.address = st.event_session_address 20 | where s.name = 'alwayson_health' 21 | and st.target_name = 'event_file' 22 | ), 23 | full_path_cte as 24 | ( 25 | select 26 | full_path = 27 | target_data.value('(EventFileTarget/File/@name)[1]', 'varchar(1024)') 28 | from target_data_cte 29 | ) 30 | select 31 | @xel_path = 32 | left(full_path, len(full_path) - charindex('\', reverse(full_path))) + 33 | '\AlwaysOn_health*.xel' 34 | from full_path_cte; 35 | 36 | ------------------------------------------------------------------------------- 37 | ------------------- replica state change events ------------------------------- 38 | ------------------------------------------------------------------------------- 39 | ;with state_change_data as 40 | ( 41 | select 42 | object_name, 43 | event_data = 44 | convert(xml, event_data) 45 | from sys.fn_xe_file_target_read_file(@xel_path, null, null, null) 46 | ) 47 | select 48 | object_name, 49 | event_timestamp = 50 | dateadd(hour, @utc_adjustment, event_data.value('(event/@timestamp)[1]', 'datetime')), 51 | ag_name = 52 | event_data.value('(event/data[@name = "availability_group_name"]/value)[1]', 'varchar(64)'), 53 | previous_state = 54 | event_data.value('(event/data[@name = "previous_state"]/text)[1]', 'varchar(64)'), 55 | current_state = 56 | event_data.value('(event/data[@name = "current_state"]/text)[1]', 'varchar(64)') 57 | from state_change_data 58 | where object_name = 'availability_replica_state_change' 59 | order by event_timestamp desc; 60 | -------------------------------------------------------------------------------- /AlwaysOn/AlwaysOn_ForceManualFailover.sql: -------------------------------------------------------------------------------- 1 | --File: AlwaysOn\AlwaysOn_ForceManualFailover.sql 2 | --Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 3 | --Added in 2022-06-24 4 | 5 | ALTER AVAILABILITY GROUP AGTest FORCE_FAILOVER_ALLOW_DATA_LOSS; 6 | 7 | --In this case we had to previousle bring the cluster up without QUORUM to make it work! -------------------------------------------------------------------------------- /AlwaysOn/AlwaysOn_sp_help_revlogin.sql: -------------------------------------------------------------------------------- 1 | --File: AlwaysOn\AlwaysOn_sp_help_revlogin.sql 2 | --Extracted from https://support.microsoft.com/en-us/help/918992/how-to-transfer-logins-and-passwords-between-instances-of-sql-server 3 | --Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 4 | --Added in 2019-08-22 5 | 6 | -- This script will create the SP sp_help_revlogin 7 | -- Once created, execute it in primary node, and then execute the result in secondary node. 8 | 9 | USE master 10 | GO 11 | IF OBJECT_ID ('sp_hexadecimal') IS NOT NULL 12 | DROP PROCEDURE sp_hexadecimal 13 | GO 14 | CREATE PROCEDURE sp_hexadecimal 15 | @binvalue varbinary(256), 16 | @hexvalue varchar (514) OUTPUT 17 | AS 18 | DECLARE @charvalue varchar (514) 19 | DECLARE @i int 20 | DECLARE @length int 21 | DECLARE @hexstring char(16) 22 | SELECT @charvalue = '0x' 23 | SELECT @i = 1 24 | SELECT @length = DATALENGTH (@binvalue) 25 | SELECT @hexstring = '0123456789ABCDEF' 26 | WHILE (@i <= @length) 27 | BEGIN 28 | DECLARE @tempint int 29 | DECLARE @firstint int 30 | DECLARE @secondint int 31 | SELECT @tempint = CONVERT(int, SUBSTRING(@binvalue,@i,1)) 32 | SELECT @firstint = FLOOR(@tempint/16) 33 | SELECT @secondint = @tempint - (@firstint*16) 34 | SELECT @charvalue = @charvalue + 35 | SUBSTRING(@hexstring, @firstint+1, 1) + 36 | SUBSTRING(@hexstring, @secondint+1, 1) 37 | SELECT @i = @i + 1 38 | END 39 | 40 | SELECT @hexvalue = @charvalue 41 | GO 42 | 43 | IF OBJECT_ID ('sp_help_revlogin') IS NOT NULL 44 | DROP PROCEDURE sp_help_revlogin 45 | GO 46 | CREATE PROCEDURE sp_help_revlogin @login_name sysname = NULL AS 47 | DECLARE @name sysname 48 | DECLARE @type varchar (1) 49 | DECLARE @hasaccess int 50 | DECLARE @denylogin int 51 | DECLARE @is_disabled int 52 | DECLARE @PWD_varbinary varbinary (256) 53 | DECLARE @PWD_string varchar (514) 54 | DECLARE @SID_varbinary varbinary (85) 55 | DECLARE @SID_string varchar (514) 56 | DECLARE @tmpstr varchar (1024) 57 | DECLARE @is_policy_checked varchar (3) 58 | DECLARE @is_expiration_checked varchar (3) 59 | 60 | DECLARE @defaultdb sysname 61 | 62 | IF (@login_name IS NULL) 63 | DECLARE login_curs CURSOR FOR 64 | 65 | SELECT p.sid, p.name, p.type, p.is_disabled, p.default_database_name, l.hasaccess, l.denylogin FROM 66 | sys.server_principals p LEFT JOIN sys.syslogins l 67 | ON ( l.name = p.name ) WHERE p.type IN ( 'S', 'G', 'U' ) AND p.name <> 'sa' 68 | ELSE 69 | DECLARE login_curs CURSOR FOR 70 | 71 | 72 | SELECT p.sid, p.name, p.type, p.is_disabled, p.default_database_name, l.hasaccess, l.denylogin FROM 73 | sys.server_principals p LEFT JOIN sys.syslogins l 74 | ON ( l.name = p.name ) WHERE p.type IN ( 'S', 'G', 'U' ) AND p.name = @login_name 75 | OPEN login_curs 76 | 77 | FETCH NEXT FROM login_curs INTO @SID_varbinary, @name, @type, @is_disabled, @defaultdb, @hasaccess, @denylogin 78 | IF (@@fetch_status = -1) 79 | BEGIN 80 | PRINT 'No login(s) found.' 81 | CLOSE login_curs 82 | DEALLOCATE login_curs 83 | RETURN -1 84 | END 85 | SET @tmpstr = '/* sp_help_revlogin script ' 86 | PRINT @tmpstr 87 | SET @tmpstr = '** Generated ' + CONVERT (varchar, GETDATE()) + ' on ' + @@SERVERNAME + ' */' 88 | PRINT @tmpstr 89 | PRINT '' 90 | WHILE (@@fetch_status <> -1) 91 | BEGIN 92 | IF (@@fetch_status <> -2) 93 | BEGIN 94 | PRINT '' 95 | SET @tmpstr = '-- Login: ' + @name 96 | PRINT @tmpstr 97 | IF (@type IN ( 'G', 'U')) 98 | BEGIN -- NT authenticated account/group 99 | 100 | SET @tmpstr = 'CREATE LOGIN ' + QUOTENAME( @name ) + ' FROM WINDOWS WITH DEFAULT_DATABASE = [' + @defaultdb + ']' 101 | END 102 | ELSE BEGIN -- SQL Server authentication 103 | -- obtain password and sid 104 | SET @PWD_varbinary = CAST( LOGINPROPERTY( @name, 'PasswordHash' ) AS varbinary (256) ) 105 | EXEC sp_hexadecimal @PWD_varbinary, @PWD_string OUT 106 | EXEC sp_hexadecimal @SID_varbinary,@SID_string OUT 107 | 108 | -- obtain password policy state 109 | SELECT @is_policy_checked = CASE is_policy_checked WHEN 1 THEN 'ON' WHEN 0 THEN 'OFF' ELSE NULL END FROM sys.sql_logins WHERE name = @name 110 | SELECT @is_expiration_checked = CASE is_expiration_checked WHEN 1 THEN 'ON' WHEN 0 THEN 'OFF' ELSE NULL END FROM sys.sql_logins WHERE name = @name 111 | 112 | SET @tmpstr = 'CREATE LOGIN ' + QUOTENAME( @name ) + ' WITH PASSWORD = ' + @PWD_string + ' HASHED, SID = ' + @SID_string + ', DEFAULT_DATABASE = [' + @defaultdb + ']' 113 | 114 | IF ( @is_policy_checked IS NOT NULL ) 115 | BEGIN 116 | SET @tmpstr = @tmpstr + ', CHECK_POLICY = ' + @is_policy_checked 117 | END 118 | IF ( @is_expiration_checked IS NOT NULL ) 119 | BEGIN 120 | SET @tmpstr = @tmpstr + ', CHECK_EXPIRATION = ' + @is_expiration_checked 121 | END 122 | END 123 | IF (@denylogin = 1) 124 | BEGIN -- login is denied access 125 | SET @tmpstr = @tmpstr + '; DENY CONNECT SQL TO ' + QUOTENAME( @name ) 126 | END 127 | ELSE IF (@hasaccess = 0) 128 | BEGIN -- login exists but does not have access 129 | SET @tmpstr = @tmpstr + '; REVOKE CONNECT SQL TO ' + QUOTENAME( @name ) 130 | END 131 | IF (@is_disabled = 1) 132 | BEGIN -- login is disabled 133 | SET @tmpstr = @tmpstr + '; ALTER LOGIN ' + QUOTENAME( @name ) + ' DISABLE' 134 | END 135 | PRINT @tmpstr 136 | END 137 | 138 | FETCH NEXT FROM login_curs INTO @SID_varbinary, @name, @type, @is_disabled, @defaultdb, @hasaccess, @denylogin 139 | END 140 | CLOSE login_curs 141 | DEALLOCATE login_curs 142 | RETURN 0 143 | GO -------------------------------------------------------------------------------- /Backups/SQLBackups_BackupAllDBsToDisk.sql: -------------------------------------------------------------------------------- 1 | --File: Backups/SQLBackups_BackupAllDBsToDisk.sql 2 | --Extracted from https://www.mssqltips.com/sqlservertip/1070/simple-script-to-backup-all-sql-server-databases/ 3 | --Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 4 | --Added in 2021-01-27 5 | 6 | DECLARE @name VARCHAR(50) -- database name 7 | DECLARE @path VARCHAR(256) -- path for backup files 8 | DECLARE @fileName VARCHAR(256) -- filename for backup 9 | DECLARE @fileDate VARCHAR(20) -- used for file name 10 | 11 | -- specify database backup directory 12 | SET @path = 'D:\DBI\Backups\' 13 | 14 | -- specify filename format 15 | SELECT @fileDate = CONVERT(VARCHAR(20),GETDATE(),112) + '_' + REPLACE(CONVERT(VARCHAR(20),GETDATE(),108),':','') 16 | 17 | DECLARE db_cursor CURSOR READ_ONLY FOR 18 | SELECT name 19 | FROM master.sys.databases 20 | WHERE name NOT IN ('master','model','msdb','tempdb') -- exclude system dbs 21 | AND state = 0 -- database is online 22 | AND is_in_standby = 0 -- database is not read only for log shipping 23 | 24 | OPEN db_cursor 25 | FETCH NEXT FROM db_cursor INTO @name 26 | 27 | WHILE @@FETCH_STATUS = 0 28 | BEGIN 29 | SET @fileName = @path + @name + '_' + @fileDate + '.BAK' 30 | BACKUP DATABASE @name TO DISK = @fileName WITH COPY_ONLY,COMPRESSION 31 | FETCH NEXT FROM db_cursor INTO @name 32 | END 33 | 34 | 35 | CLOSE db_cursor 36 | DEALLOCATE db_cursor -------------------------------------------------------------------------------- /Backups/SQLBackups_BackupEstimations.sql: -------------------------------------------------------------------------------- 1 | --File: Backups/SQLBackups_BackupEstimations.sql 2 | --Extracted from https://www.mssqltips.com/sqlservertip/5253/sql-server-stored-procedure-to-calculate-database-backup-compression-ratio/ 3 | --Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 4 | --Added in 2019-06-25 5 | 6 | -- Create this SP and then call it (see how at the bottom) 7 | USE master 8 | GO 9 | 10 | CREATE PROCEDURE usp_Calc_DB_Compression_Ratio_Pct ( 11 | @dbName SYSNAME, 12 | @compressPct DECIMAL (5, 1) OUTPUT 13 | ) 14 | AS 15 | BEGIN 16 | DECLARE @dynaTSQL VARCHAR(400) 17 | 18 | SET NOCOUNT ON 19 | SET @dynaTSQL = CONCAT ( 20 | 'BACKUP DATABASE ', 21 | @dbName, 22 | ' TO DISK = N', 23 | '''', 24 | 'nul', 25 | '''', 26 | ' with compression, copy_only ' 27 | ) 28 | 29 | EXEC (@dynaTSQL) 30 | 31 | SELECT @compressPct = cast (100.0*a.compressed_backup_size / a.backup_size AS DECIMAL (5, 1)) 32 | FROM msdb..backupset a 33 | WHERE lower (a.database_name) = @dbName AND a.backup_finish_date = ( 34 | SELECT max (backup_finish_date) 35 | FROM msdb..backupset 36 | ) 37 | 38 | SET NOCOUNT OFF 39 | END 40 | GO 41 | 42 | -- To get the estimation 43 | USE master 44 | GO 45 | 46 | DECLARE @comppct DECIMAL (5, 1) 47 | 48 | EXEC usp_Calc_DB_Compression_Ratio_Pct @dbname = 'Northwind', 49 | @compressPct = @comppct OUTPUT 50 | 51 | PRINT @comppct 52 | -------------------------------------------------------------------------------- /Backups/SQLBackups_BackupsChain.sql: -------------------------------------------------------------------------------- 1 | --File: Backups/SQLBackups_BackupsChain.sql 2 | --Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 3 | --Added in 2019-05 4 | 5 | -- CHECK DIFFERENTIAL DB BACKUPS SET (CHAIN) 6 | SELECT 7 | s.backup_start_date as 'Start Date', 8 | s.backup_finish_date as 'Full Date', 9 | CONVERT(varchar, s.backup_finish_date, 103) as 'Date', 10 | CONVERT(VARCHAR(8),s.backup_finish_date,108) as 'Time', 11 | DATEDIFF(minute, s.backup_start_date, s.backup_finish_date) as 'Duration (minutes)', 12 | s.database_name as 'Database Name', 13 | CAST(s.backup_size / (1024*1024) as int) as 'DBSize (MBs)', 14 | CASE 15 | WHEN (s.[type] = 'D' AND s.is_copy_only = 0) THEN 'Full' 16 | WHEN (s.[type] = 'D' AND s.is_copy_only = 1) THEN 'Full - CopyOnly' 17 | WHEN (s.[type] = 'I') THEN 'Differential database' 18 | WHEN (s.[type] = 'L') THEN 'Log' 19 | WHEN (s.[type] = 'F') THEN 'File or filegroup' 20 | WHEN (s.[type] = 'G') THEN 'Differential file' 21 | WHEN (s.[type] = 'P') THEN 'Partial' 22 | WHEN (s.[type] = 'G') THEN 'Differential partial' 23 | ELSE NULL 24 | END AS BackupType, 25 | s.is_damaged, 26 | m.physical_device_name as 'Backup Device', 27 | t.physical_device_name as 'Differential base - Device', 28 | t.backup_finish_date as 'Differential base - Full Date', 29 | s.[user_name] as [User] 30 | FROM msdb.dbo.backupset s 31 | INNER JOIN msdb.dbo.backupmediafamily m ON s.media_set_id = m.media_set_id 32 | LEFT JOIN 33 | (SELECT ss.backup_set_uuid, ss.backup_finish_date, mm.physical_device_name 34 | FROM msdb.dbo.backupset ss 35 | INNER JOIN msdb.dbo.backupmediafamily mm ON ss.media_set_id = mm.media_set_id 36 | ) as t 37 | ON s.differential_base_guid = t.backup_set_uuid 38 | order by s.backup_start_date desc 39 | GO 40 | -------------------------------------------------------------------------------- /Backups/SQLBackups_BackupsDone.sql: -------------------------------------------------------------------------------- 1 | --File: Backups/SQLBackups_BackupsDone.sql 2 | --Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 3 | --Added in 2019-06-25 4 | 5 | --CHECK ALL BACKUPS DONE AND TIME TAKEN 6 | SELECT TOP 100 7 | s.database_name, 8 | m.physical_device_name, 9 | CAST(CAST(s.backup_size / 1000000 AS INT) AS VARCHAR(14)) + ' ' + 'MB' AS bkSize, 10 | CAST(CAST(s.compressed_backup_size / 1000000 AS INT) AS VARCHAR(14)) + ' ' + 'MB' AS bkCompressedSize, 11 | CAST(DATEDIFF(second, s.backup_start_date, 12 | s.backup_finish_date) AS VARCHAR(15)) + ' ' + 'Seconds' TimeTaken, 13 | s.backup_start_date, 14 | --CAST(s.first_lsn AS VARCHAR(50)) AS first_lsn, 15 | --CAST(s.last_lsn AS VARCHAR(50)) AS last_lsn, 16 | CASE s.[type] 17 | WHEN 'D' THEN 'Full' 18 | WHEN 'I' THEN 'Differential' 19 | WHEN 'L' THEN 'Transaction Log' 20 | END AS BackupType, 21 | s.server_name, 22 | s.recovery_model 23 | FROM msdb.dbo.backupset s 24 | INNER JOIN msdb.dbo.backupmediafamily m ON s.media_set_id = m.media_set_id 25 | WHERE s.database_name = DB_NAME() -- Commnent this line for all the database 26 | AND s.type='D' --configure this line to choose the backup type to show (D/I/L) 27 | --AND database_name NOT IN ('master','msdb','model','distribution') -- Uncomment this line to exclude system dbs 28 | ORDER BY backup_start_date DESC, backup_finish_date 29 | GO -------------------------------------------------------------------------------- /Backups/SQLBackups_LatestDBBackups.sql: -------------------------------------------------------------------------------- 1 | --File: Backups/SQLBackups_LatestDBBackups.sql 2 | --Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 3 | --Added in 2019-05-31 4 | --Commentaries: Check last backup per DB in the instance 5 | 6 | --CHECK Latest DB Backups (Full, Differential and T-log) 7 | SELECT bu.* 8 | ,recovery_model_Desc AS [recovery_model] 9 | ,ISNULL(db.state_desc,'UNKNOWN') AS database_state 10 | FROM ( 11 | SELECT server_name 12 | ,database_name 13 | ,CASE 14 | WHEN physical_device_name LIKE 'TDPSQL%' THEN 'TDP' 15 | WHEN physical_device_name LIKE 'EMC#%' THEN 'NETWORKER' 16 | WHEN physical_device_name LIKE '{%' THEN 'TSMVE' 17 | ELSE 'DISK' 18 | END As Method 19 | ,CASE [type] 20 | WHEN 'D' THEN 'Full' 21 | WHEN 'I' THEN 'Differential' 22 | WHEN 'L' THEN 'Transaction_Log' 23 | END As Type 24 | ,MAX(backup_finish_date) AS lastBackup 25 | FROM msdb..backupset s 26 | INNER JOIN msdb.dbo.backupmediafamily m ON s.media_set_id = m.media_set_id 27 | WHERE server_name = @@SERVERNAME 28 | AND database_name NOT IN ('master','msdb','model','distribution') -- Comment to include system dbs 29 | --AND backup_finish_date between '2019-01-01 10:00' and '2019-04-16 09:00' 30 | GROUP BY server_name 31 | ,database_name 32 | ,CASE 33 | WHEN physical_device_name LIKE 'TDPSQL%' THEN 'TDP' 34 | WHEN physical_device_name LIKE 'EMC#%' THEN 'NETWORKER' 35 | WHEN physical_device_name LIKE '{%' THEN 'TSMVE' 36 | ELSE 'DISK' END 37 | ,type 38 | ) AS SourceTable PIVOT (max(lastBackup) FOR Type IN ([Full],[Differential],[Transaction_Log])) As bu 39 | LEFT JOIN master.sys.databases db ON bu.database_name = db.name 40 | WHERE Method = 'TDP' -- Possible methods TDP, TSMVE, NETWORKER or DISK 41 | AND db.state_desc IS NOT NULL --Comment to include dbs not available any longer in the server. 42 | ORDER BY bu.database_name -------------------------------------------------------------------------------- /Backups/SQLBackups_Progress.sql: -------------------------------------------------------------------------------- 1 | --File: Backups/SQLBackups_Progress.sql 2 | --Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 3 | --Added in 2019-06-25 4 | 5 | --BACKUP - PROGRESS (%) 6 | SELECT r.session_id, 7 | r.command, 8 | CONVERT(NUMERIC(6,2),r.percent_complete) AS [Percent Complete], 9 | CONVERT(VARCHAR(20),DATEADD(ms,r.estimated_completion_time,GetDate()),20) AS [ETA Completion Time], 10 | CONVERT(NUMERIC(10,2),r.total_elapsed_time/1000.0/60.0) AS [Elapsed Min], 11 | CONVERT(NUMERIC(10,2),r.estimated_completion_time/1000.0/60.0) AS [ETA Min], 12 | CONVERT(NUMERIC(10,2),r.estimated_completion_time/1000.0/60.0/60.0) AS [ETA Hours], 13 | CONVERT(VARCHAR(1000),( 14 | SELECT SUBSTRING(text,r.statement_start_offset/2, 15 | CASE WHEN r.statement_end_offset = -1 THEN 1000 ELSE (r.statement_end_offset-r.statement_start_offset)/2 END) 16 | FROM sys.dm_exec_sql_text(sql_handle))) 17 | FROM sys.dm_exec_requests r 18 | WHERE command IN ('RESTORE DATABASE','BACKUP DATABASE','RESTORE LOG','BACKUP LOG','RESTORE HEADERONLY') -------------------------------------------------------------------------------- /Backups/SQLBackups_RestoresDone.sql: -------------------------------------------------------------------------------- 1 | --File: Backups/SQLBackups_RestoresDone.sql 2 | --Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 3 | --Added in 2019-06-25 4 | 5 | --CHECK DB RESTORES 6 | SELECT [rs].[restore_date], 7 | CASE [rs].[restore_type] 8 | WHEN 'D' THEN 'Full' 9 | WHEN 'I' THEN 'Differential' 10 | WHEN 'L' THEN 'Transaction Log' 11 | END AS RestoreType, 12 | [rs].[destination_database_name], 13 | rs.user_name as 'RestoredBy', 14 | CASE rs.[replace] 15 | WHEN NULL THEN 'NULL' 16 | WHEN 1 THEN 'YES' 17 | WHEN 0 THEN 'NO' 18 | END AS 'Database Replaced', 19 | [bs].[backup_start_date], 20 | [bs].[backup_finish_date], 21 | [bs].[database_name] as [source_database_name], 22 | [bmf].[physical_device_name] as [backup_file_used_for_restore] 23 | FROM msdb..restorehistory rs 24 | INNER JOIN msdb..backupset bs ON [rs].[backup_set_id] = [bs].[backup_set_id] 25 | INNER JOIN msdb..backupmediafamily bmf ON [bs].[media_set_id] = [bmf].[media_set_id] 26 | ORDER BY [rs].[restore_date] DESC -------------------------------------------------------------------------------- /Backups/TDP/Backups_TDP_CheckBackups.ps1: -------------------------------------------------------------------------------- 1 | # File: Backups\TDP\Backups_TDP_CheckBackups.ps1 2 | # Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 3 | # Added in 2019-12-16 4 | # Commentaries: Check Backups made with Tivoli TSM in a server 5 | 6 | Import-Module (Get-ChildItem (Get-ItemProperty -Path "HKLM:\SOFTWARE\IBM\FlashCopyManager\CurrentVersion\mmc").Path -Filter fmmodule*.dll).FullName 7 | Get-DpSqlBackup -Name * -AllTypes -All -COMPATibilityinfo -FROMSQLserver * -QUERYNode DP -ConfigFile "" -TsmOptFile "" 8 | -------------------------------------------------------------------------------- /Collations/Collations_CollationChange.cmd: -------------------------------------------------------------------------------- 1 | ::File: Collation/CollationChange.cmd 2 | ::Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 3 | ::Added in 2019-0820 4 | ::Commentaries: SQL Service must be stopped. 5 | ::Origin: https://www.mssqltips.com/sqlservertip/3519/changing-sql-server-collation-after-installation/ 6 | 7 | sqlservr -m -T4022 -T3659 -q"SQL_Latin1_General_CP1_CI_AI" -------------------------------------------------------------------------------- /Connectivity/Connectivity_CheckKerberos.sql: -------------------------------------------------------------------------------- 1 | -- File: Connectivity_CheckKerberos.sql 2 | -- Extracted from "Unkown" 3 | -- Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 4 | -- Added in 2019-10-31 5 | 6 | -- To check if your connections are using KERBEROS (check from a remote host) 7 | -- SPNs should be configured for the service account that runs the SQL services & Delegation also configured 8 | 9 | SELECT auth_scheme, net_transport, session_id 10 | FROM sys.dm_exec_connections 11 | WHERE session_id = @@SPID 12 | 13 | /* Correct configuration output 14 | auth_scheme net_transport session_id 15 | KERBEROS TCP 60 <-- Executed from a remote server 16 | NTLM Shared memory 64 <-- Executed from the same server 17 | */ -------------------------------------------------------------------------------- /Connectivity/Connectivity_CheckSPNs.cmd: -------------------------------------------------------------------------------- 1 | :: File: Connectivity_CheckSPNs.cmd 2 | :: Extracted from "Unkown" 3 | :: Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 4 | :: Added in 2019-10-31 5 | 6 | :: List SPNs registered for a SQL Server, searching by service account (try with and witout domain) 7 | setspn -l 8 | 9 | :: Example of a correct output 10 | :: C:\> setspn -q MSSQLSvc/mymachine.mydomain.com:1433 11 | :: Checking domain DC=domain1,DC=com 12 | :: CN=ServiceAccountName,OU=Service Accounts,OU=OUName,OU=EMEA,DC=zurich,DC=uat 13 | :: MSSQLSvc/mymachine:1433 14 | :: MSSQLSvc/mymachine.mydomain.com:1433 15 | 16 | 17 | :: List SPNs registered for a SQL Server, searching by server 18 | setspn -q MSSQLSvc/: 19 | 20 | :: Example of a correct output 21 | :: C:>setspn -q MSSQLSvc/mymachine.mydomain.com:1433 22 | :: Registered ServicePrincipalNames for CN=MYSERVICEACCOUNT,OU=Service Accounts,DC=mydomain,DC=com 23 | :: MSSQLSvc/mymachine:1433 24 | :: MSSQLSvc/mymachine.mydomain.com:1433 -------------------------------------------------------------------------------- /DBStatus/DB_RepairADBInSuspectState.sql: -------------------------------------------------------------------------------- 1 | --REPAIR A DB IN SUSPECT STATE 2 | --REPLACE WITH THE REAL DB NAME 3 | 4 | ALTER DATABASE [] SET EMERGENCY 5 | DBCC checkdb([]) 6 | ALTER DATABASE [] SET SINGLE_USER WITH ROLLBACK IMMEDIATE 7 | DBCC CheckDB ([], REPAIR_ALLOW_DATA_LOSS) 8 | ALTER DATABASE [] SET MULTI_USER -------------------------------------------------------------------------------- /DBStatus/SQLInstance_RecoverAllDBsInSuspectState.sql: -------------------------------------------------------------------------------- 1 | --REPAIR ALL DBS IN SUSPECT STATE 2 | --REMEMBER TO CHECK THE RESULTS TO SEE IF THERE WAS DATA LOSS 3 | 4 | declare @database as nvarchar(40) 5 | declare @CMD as nvarchar(250) 6 | 7 | declare suspect_dbs cursor for 8 | select name from sys.databases where state_desc='SUSPECT' 9 | 10 | open suspect_dbs 11 | fetch next from suspect_dbs into @database 12 | while @@FETCH_STATUS=0 13 | begin 14 | set @CMD='ALTER DATABASE ['+@database+'] SET EMERGENCY' 15 | print @CMD 16 | exec sp_executesql @CMD 17 | set @CMD='DBCC checkdb(['+@database+'])' 18 | print @CMD 19 | exec sp_executesql @CMD 20 | SET @CMD='ALTER DATABASE ['+@database+'] SET SINGLE_USER WITH ROLLBACK IMMEDIATE' 21 | print @CMD 22 | exec sp_executesql @CMD 23 | SET @CMD='DBCC CheckDB (['+@database+'], REPAIR_ALLOW_DATA_LOSS)' 24 | print @CMD 25 | exec sp_executesql @CMD 26 | SET @CMD='ALTER DATABASE ['+@database+'] SET MULTI_USER' 27 | print @CMD 28 | exec sp_executesql @CMD 29 | fetch next from suspect_dbs into @database 30 | end 31 | 32 | close suspect_dbs 33 | deallocate suspect_dbs -------------------------------------------------------------------------------- /DBStatus/SQLInstance_RecoverAllDBsInSuspectState2.sql: -------------------------------------------------------------------------------- 1 | DECLARE @P1 int, @P2 int, @P3 int, @P4 int, @P5 int; 2 | DECLARE @database AS nvarchar(40) 3 | 4 | EXEC sp_prepare @P1 output,N'@database nvarchar(40)',N'ALTER DATABASE [@database] SET EMERGENCY'; 5 | EXEC sp_prepare @P2 output,N'@database nvarchar(40)',N'DBCC CHECKDB([@database])'; 6 | EXEC sp_prepare @P3 output,N'@database nvarchar(40)',N'ALTER DATABASE [@database] SET SINGLE_USER WITH ROLLBACK IMMEDIATE'; 7 | EXEC sp_prepare @P4 output,N'@database nvarchar(40)',N'DBCC CHECKDB ([@database], REPAIR_ALLOW_DATA_LOSS)'; 8 | EXEC sp_prepare @P5 output,N'@database nvarchar(40)',N'ALTER DATABASE [@database] SET MULTI_USER'; 9 | 10 | DECLARE suspect_dbs CURSOR FOR 11 | SELECT name FROM sys.databases WHERE state_desc='SUSPECT' 12 | 13 | OPEN suspect_dbs 14 | FETCH NEXT FROM suspect_dbs INTO @database 15 | PRINT 'Databases in suspect status: '+CAST(@@CURSOR_ROWS AS varchar(100)) 16 | 17 | WHILE @@FETCH_STATUS=0 18 | BEGIN 19 | PRINT 'Fixing database: '+@database 20 | EXEC sp_execute @P1, N'database', @database; 21 | EXEC sp_execute @P2, N'database', @database; 22 | EXEC sp_execute @P3, N'database', @database; 23 | EXEC sp_execute @P4, N'database', @database; 24 | EXEC sp_execute @P5, N'database', @database; 25 | FETCH NEXT FROM suspect_dbs INTO @database 26 | END 27 | 28 | CLOSE suspect_dbs 29 | DEALLOCATE suspect_dbs 30 | 31 | EXEC sp_unprepare @P1; 32 | EXEC sp_unprepare @P2; 33 | EXEC sp_unprepare @P3; 34 | EXEC sp_unprepare @P4; 35 | EXEC sp_unprepare @P5; 36 | -------------------------------------------------------------------------------- /Databases/Databases_CheckShrinkProgress.sql: -------------------------------------------------------------------------------- 1 | --File: Databases/Databases_CheckShrinkProgress.sql 2 | --Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 3 | --Added in 2022-06-10 4 | 5 | --Track DBCC shrink status 6 | select 7 | a.session_id 8 | , command 9 | , b.text 10 | , percent_complete 11 | , done_in_minutes = a.estimated_completion_time / 1000 / 60 12 | , min_in_progress = DATEDIFF(MI, a.start_time, DATEADD(ms, a.estimated_completion_time, GETDATE() )) 13 | , a.start_time 14 | , estimated_completion_time = DATEADD(ms, a.estimated_completion_time, GETDATE() ) 15 | from sys.dm_exec_requests a 16 | CROSS APPLY sys.dm_exec_sql_text(a.sql_handle) b 17 | where command like '%dbcc%' -------------------------------------------------------------------------------- /Databases/Databases_CheckVlogsForShrink.sql: -------------------------------------------------------------------------------- 1 | --File: Databases/Databases_CheckVlogsForShrink.sql 2 | --Inspired in https://docs.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-db-log-info-transact-sql?view=sql-server-ver15 3 | --Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 4 | --Added in 2021-11-24 5 | 6 | ;WITH cte_vlf AS ( 7 | SELECT ROW_NUMBER() OVER(PARTITION BY s.database_id ORDER BY vlf_begin_offset) AS vlfid 8 | , DB_NAME(s.database_id) AS [Database Name] 9 | , vlf_sequence_number 10 | , vlf_active 11 | , vlf_begin_offset 12 | , vlf_size_mb 13 | FROM sys.databases s 14 | CROSS APPLY sys.dm_db_log_info(s.database_id) l 15 | --WHERE DB_NAME(s.database_id) IN ('CHRXS1DBREPOSITORY','BlackBox') 16 | ),cte_vlf_cnt AS ( 17 | SELECT [Database Name] 18 | , COUNT(vlf_sequence_number) AS vlf_count 19 | , SUM(IIF(vlf_active=0,1,0)) AS vlf_count_inactive 20 | , SUM(IIF(vlf_active=1,1,0)) AS vlf_count_active 21 | , MIN(IIF(vlf_active=1,vlfid,NULL)) AS ordinal_min_vlf_active 22 | , MIN(IIF(vlf_active=1,vlf_sequence_number,NULL)) AS min_vlf_active 23 | , MAX(IIF(vlf_active=1,vlfid,NULL)) AS ordinal_max_vlf_active 24 | , MAX(IIF(vlf_active=1,vlf_sequence_number,NULL)) AS max_vlf_active 25 | FROM cte_vlf cv 26 | GROUP BY [Database Name] 27 | ) --SELECT * FROM cte_vlf_cnt 28 | SELECT [Database Name] 29 | , vlf_count 30 | , min_vlf_active 31 | , ordinal_min_vlf_active 32 | , max_vlf_active 33 | , ordinal_max_vlf_active 34 | , FORMAT((ordinal_min_vlf_active-1)*1.0/vlf_count,'P2') AS free_log_pct_before_active_log 35 | , FORMAT((ordinal_max_vlf_active-(ordinal_min_vlf_active-1))*1.0/vlf_count,'P2') AS active_log_pct 36 | , FORMAT((vlf_count-ordinal_max_vlf_active)*1.0/vlf_count,'P2') AS free_log_pct_after_active_log 37 | , ((vlf_count-ordinal_max_vlf_active)*100.00/vlf_count) 38 | FROM cte_vlf_cnt -------------------------------------------------------------------------------- /Databases/Databases_DatafileSplitProgressCheck.sql: -------------------------------------------------------------------------------- 1 | --File: Databases/Database_DatafileSplitProgressCheck.sql 2 | --Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 3 | --Added in 2021-10-14 4 | 5 | 6 | SELECT @@servername as SQLInstance 7 | , DB_NAME() AS DBName 8 | , name AS FileName 9 | , type_desc 10 | , size/128.0 AS CurrentSizeMB 11 | , CAST(FILEPROPERTY(name, 'SpaceUsed') AS INT)/128.0 AS UsedMB 12 | , size/128.0 - CAST(FILEPROPERTY(name, 'SpaceUsed') AS INT)/128.0 AS FreeSpaceMB 13 | , max_size/128.0 AS MaxSizeMB 14 | FROM sys.database_files 15 | WHERE type IN (0,1) 16 | ORDER BY type,name -------------------------------------------------------------------------------- /Databases/Databases_FindATableInAllDBs.sql: -------------------------------------------------------------------------------- 1 | --File: Databases/Databases_FindATableInAllDBs.sql 2 | --Extracted from https://stackoverflow.com/questions/18141547/display-all-the-names-of-databases-containing-particular-table 3 | --Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 4 | --Added in 2022-01-10 5 | 6 | SELECT name 7 | FROM sys.databases 8 | WHERE CASE WHEN state_desc = 'ONLINE' THEN OBJECT_ID(QUOTENAME(name) + '..','U') END IS NOT NULL 9 | 10 | 11 | --OR even better 12 | --Extracted from https://social.technet.microsoft.com/wiki/contents/articles/17958.find-a-table-on-a-sql-server-across-all-databases.aspx 13 | --Added in 2022-04-21 14 | 15 | sp_MSforeachdb 'SELECT "?" AS DB, * FROM [?].sys.tables WHERE name like ''%
%''' -------------------------------------------------------------------------------- /Databases/Databases_GetFileSizes.sql: -------------------------------------------------------------------------------- 1 | --File: Databases/Databases_GetFileSizes.sql 2 | --Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 3 | --Added in 2022-04-07 4 | 5 | DECLARE @FileType NVARCHAR(5) = '%' --Possible values: ROWS & LOG, use % for all files 6 | DECLARE @OnlyUserDBs bit = 0 --Possible values: 0: include all dbs, 1: include only UserDBs 7 | 8 | DECLARE @SqlStatement nvarchar(MAX); 9 | CREATE TABLE #DatabaseSpace (DBName sysname, [FileName] sysname, Used_KB bigint); 10 | 11 | SET @SqlStatement= N'USE [?]; 12 | SELECT DB_NAME(), f.name, CONVERT(bigint,fileproperty(f.name,''SpaceUsed''))*8 13 | FROM sys.database_files f;'; 14 | 15 | INSERT INTO #DatabaseSpace 16 | EXECUTE sp_MSforeachdb @SqlStatement; 17 | 18 | SELECT DB_NAME(f.database_id) AS DBName 19 | ,f.name AS [FileName] 20 | ,f.type_desc 21 | ,volume_mount_point 22 | ,CAST(total_bytes/1024.0/1024.0/1024.0 AS decimal(12,2)) AS DriveSize_GB 23 | ,CAST(available_bytes /1024.0/1024.0/1024.0 AS decimal(12,2)) AS DriveFree_GB 24 | ,CAST(Used_KB/1024.0/1024.0 AS decimal(12,2)) AS Used_GB 25 | ,CAST(size/128.0/1024.0 AS decimal(12,2)) AS FileSize_GB 26 | ,CAST(CASE --not taking in account if autogrowth is disabled 27 | WHEN max_size=0 THEN size/128.0/1024.0 --it will grow until current file gets full. 28 | WHEN max_size=-1 THEN total_bytes/1024.0/1024.0/1024.0 --datafile that will grow until drive is full 29 | ELSE max_size/128.0/1024.0 30 | END AS decimal(12,2)) AS FileMaxSize_GB 31 | ,CAST(CASE --taking in account if autogrowth is disabled 32 | WHEN growth=0 OR max_size=0 THEN size/128.0/1024.0 --Autogrowth disabled, so it will grow until current file gets full. 33 | WHEN max_size=-1 THEN total_bytes/1024.0/1024.0/1024.0 --datafile that will grow until drive is full 34 | ELSE max_size/128.0/1024.0 35 | END AS decimal(12,2)) AS RealFileMaxSize_GB 36 | ,CASE f.growth 37 | WHEN 0 THEN 'Disabled' 38 | ELSE 'By '+IIF(f.is_percent_growth = 1, CAST(f.growth AS VARCHAR(12))+'%', CONVERT(VARCHAR(30), CAST((f.growth*8) / 1024.0 AS DECIMAL(12,2)))+' MB') 39 | END AS [Autogrowth] 40 | FROM sys.master_files AS f 41 | CROSS APPLY sys.dm_os_volume_stats(f.database_id, f.file_id) 42 | INNER JOIN #DatabaseSpace ds ON DB_NAME(f.database_id)=ds.DBName AND f.name=ds.FileName 43 | WHERE type_desc LIKE @FileType 44 | AND (@OnlyUserDBs=0 OR DB_NAME(f.database_id) NOT IN ('master','model','msdb','tempdb')) --To exclude system DBs 45 | AND (@OnlyUserDBs=0 OR DB_NAME(f.database_id) NOT LIKE 'CHRX%') --To exclude any other management DBs 46 | ORDER BY DB_NAME(f.database_id),f.type_desc,f.name ASC 47 | 48 | DROP TABLE #DatabaseSpace 49 | -------------------------------------------------------------------------------- /Databases/Databases_GetTablesSize.sql: -------------------------------------------------------------------------------- 1 | --File: Databases/Databases_FindATableInAllDBs.sql 2 | --Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 3 | --Added in 2020-03-18 4 | 5 | --Extracted from https://stackoverflow.com/questions/1443704/query-to-list-number-of-records-in-each-table-in-a-database 6 | 7 | SELECT 8 | t.NAME AS TableName, 9 | i.name as indexName, 10 | p.[Rows], 11 | sum(a.total_pages) as TotalPages, 12 | sum(a.used_pages) as UsedPages, 13 | sum(a.data_pages) as DataPages, 14 | (sum(a.total_pages) * 8) / 1024 as TotalSpaceMB, 15 | (sum(a.used_pages) * 8) / 1024 as UsedSpaceMB, 16 | (sum(a.data_pages) * 8) / 1024 as DataSpaceMB 17 | FROM sys.tables t 18 | INNER JOIN sys.indexes i ON t.OBJECT_ID = i.object_id 19 | INNER JOIN sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id 20 | INNER JOIN sys.allocation_units a ON p.partition_id = a.container_id 21 | WHERE t.NAME NOT LIKE 'dt%' 22 | AND i.OBJECT_ID > 255 23 | AND i.index_id <= 1 24 | GROUP BY t.NAME, i.object_id, i.index_id, i.name, p.[Rows] 25 | ORDER BY object_name(i.object_id) 26 | 27 | 28 | --Extracted from: https://blogs.msdn.microsoft.com/martijnh/2010/07/15/sql-serverhow-to-quickly-retrieve-accurate-row-count-for-table/ 29 | 30 | SELECT 31 | SCHEMA_NAME(schema_id) AS [SchemaName], 32 | [Tables].name AS [TableName], 33 | SUM([Partitions].[rows]) AS [TotalRowCount] 34 | FROM sys.tables AS [Tables] 35 | JOIN sys.partitions AS [Partitions] ON [Tables].[object_id] = [Partitions].[object_id] 36 | AND [Partitions].index_id IN (0,1) 37 | -- WHERE [Tables].name = N'name of the table' 38 | GROUP BY SCHEMA_NAME(schema_id), [Tables].name; -------------------------------------------------------------------------------- /Databases/Databases_RenameDB.sql: -------------------------------------------------------------------------------- 1 | --File: Databases/Databases_RenameDB.sql 2 | --Extracted from https://www.mssqltips.com/sqlservertip/1070/simple-script-to-backup-all-sql-server-databases/ 3 | --Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 4 | --Added in 2021-08-31 5 | 6 | DECLARE @OLD_DBNAME varchar(30) -- Nombre Actual DB 7 | DECLARE @NEW_DBNAME varchar(30) --Nuevo Nombre DB 8 | DECLARE @OLD_DATA_LOGICALNAME varchar(50) -- Nombre Logico del grupo Primario de Datos actual 9 | DECLARE @NEW_DATA_LOGICALNAME varchar(50) -- Nuevo Nombre Logico del grupo Primario de Datos 10 | DECLARE @OLD_LOG_LOGICALNAME varchar(50) -- Nombre Logico del grupo Primario de Log actual 11 | DECLARE @NEW_LOG_LOGICALNAME varchar(50) -- Nuevo Nombre Lógico del grupo de Log Primario 12 | DECLARE @OLD_DATA_PHYSICALNAME varchar(200) -- Nombre Fisico del grupo Primario de Datos actual 13 | DECLARE @NEW_DATA_PHYSICALNAME varchar(200) -- Nuevo Nombre Fisico del grupo Primario de Datos 14 | DECLARE @OLD_LOG_PHYSICALNAME varchar(200) -- Nombre Fisico del grupo Primario de Log actual 15 | DECLARE @NEW_LOG_PHYSICALNAME varchar(200) -- Nuevo Nombre Fisico Lógico del grupo de Log Primario 16 | DECLARE @NEW_SO_DATA_PHYSICALNAME varchar(50) 17 | DECLARE @NEW_SO_LOG_PHYSICALNAME varchar(50) 18 | DECLARE @CMD varchar(200) 19 | /* Ejecutar la siguiente Query para extraer los nombres de los ficheros logicos y fisicos que componen una DB 20 | SELECT f.name AS [File Name] , f.physical_name AS [Physical Name], 21 | CAST((f.size/128.0) AS DECIMAL(15,2)) AS [Total Size in MB], 22 | CAST(f.size/128.0 - CAST(FILEPROPERTY(f.name, 'SpaceUsed') AS int)/128.0 AS DECIMAL(15,2)) 23 | AS [Available Space In MB], f.[file_id], fg.name AS [Filegroup Name], 24 | f.is_percent_growth, f.growth, 25 | fg.is_default, fg.is_read_only 26 | FROM sys.database_files AS f WITH (NOLOCK) 27 | LEFT OUTER JOIN sys.filegroups AS fg WITH (NOLOCK) 28 | ON f.data_space_id = fg.data_space_id 29 | ORDER BY f.[file_id] OPTION (RECOMPILE); 30 | */ 31 | 32 | /* 33 | La Query anterior nos devolvera algo similar a lo siguiente 34 | File Name Physical Name 35 | CHRXS1Prueba_change E:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\CHRXS1Prueba_change.mdf 36 | CHRXS1Prueba_change_log F:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\CHRXS1Prueba_change_log.ldf 37 | */ 38 | --------------------------------------------------------------------------------------------------------------------------------------------- 39 | --------------------------------------------------------------------------------------------------------------------------------------------- 40 | --------------------------------------------------------------------------------------------------------------------------------------------- 41 | --VARIABLES ASSIGNMENT SECTION 42 | --------------------------------------------------------------------------------------------------------------------------------------------- 43 | --Example DB name is named as "CHRXS1Prueba_change" and then target DB name will be as "CHRXS1Prueba_change_B" 44 | --REMINDER!!! IMPORTANT: USE [XXXXX] FOR OBJECT NAMES WITH SPECIAL CHARACTERS (-, /, SPACE, _, ETC...) AS SHOWN BELOW 45 | SET @OLD_DBNAME = '[CHRXS1Prueba_change]' 46 | SET @NEW_DBNAME = '[CHRXS1Prueba_change_B]' 47 | SET @OLD_DATA_LOGICALNAME = '[CHRXS1Prueba_change]' 48 | SET @NEW_DATA_LOGICALNAME = '[CHRXS1Prueba_change_B]' 49 | SET @OLD_LOG_LOGICALNAME = '[CHRXS1Prueba_change_log]' 50 | SET @NEW_LOG_LOGICALNAME = '[CHRXS1Prueba_change_B_log]' 51 | SET @OLD_DATA_PHYSICALNAME = 'E:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\CHRXS1Prueba_change.mdf' 52 | SET @NEW_DATA_PHYSICALNAME = 'E:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\CHRXS1Prueba_change_B.mdf' 53 | SET @NEW_SO_DATA_PHYSICALNAME = 'CHRXS1Prueba_change_B.mdf' 54 | SET @OLD_LOG_PHYSICALNAME = 'F:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\CHRXS1Prueba_change_log.ldf' 55 | SET @NEW_LOG_PHYSICALNAME = 'F:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\CHRXS1Prueba_change_B_log.ldf' 56 | SET @NEW_SO_LOG_PHYSICALNAME = 'CHRXS1Prueba_change_B_log.ldf' 57 | 58 | --------------------------------------------------------------------------------------------------------------------------------------------- 59 | --------------------------------------------------------------------------------------------------------------------------------------------- 60 | --------------------------------------------------------------------------------------------------------------------------------------------- 61 | 62 | -- Set Database as a Single User 63 | EXEC('ALTER DATABASE '+ @OLD_DBNAME +' SET SINGLE_USER WITH ROLLBACK IMMEDIATE') 64 | 65 | -- Change Logical File Name 66 | EXEC('ALTER DATABASE '+ @OLD_DBNAME + ' MODIFY FILE (NAME='+ @OLD_DATA_LOGICALNAME +', NEWNAME='+ @NEW_DATA_LOGICALNAME +')') 67 | EXEC('ALTER DATABASE '+ @OLD_DBNAME + ' MODIFY FILE (NAME='+ @OLD_LOG_LOGICALNAME +', NEWNAME='+ @NEW_LOG_LOGICALNAME +')') 68 | 69 | --Change physical name 70 | EXEC('ALTER DATABASE '+@OLD_DBNAME+' MODIFY FILE (NAME = '+@NEW_DATA_LOGICALNAME+', FILENAME = "'+@NEW_DATA_PHYSICALNAME+'")') 71 | EXEC('ALTER DATABASE '+@OLD_DBNAME+' MODIFY FILE (NAME = '+@NEW_LOG_LOGICALNAME+', FILENAME = "'+@NEW_LOG_PHYSICALNAME+'")') 72 | 73 | --change database name 74 | USE master; 75 | EXEC('ALTER DATABASE '+@OLD_DBNAME+' Modify Name = '+@NEW_DBNAME) 76 | 77 | --SET DATABASE OFFLINE 78 | EXEC('ALTER DATABASE '+@NEW_DBNAME+ ' SET OFFLINE') 79 | 80 | --change physical name at os level 81 | -- Cambio DATA 82 | SET @CMD= 'RENAME "'+@OLD_DATA_PHYSICALNAME+'","'+@NEW_SO_DATA_PHYSICALNAME+'"' 83 | exec xp_cmdshell @CMD 84 | --Cambio el Log 85 | SET @CMD= 'RENAME "'+@OLD_LOG_PHYSICALNAME+'","'+@NEW_SO_LOG_PHYSICALNAME+'"' 86 | exec xp_cmdshell @CMD 87 | 88 | --SET DATABASE ONLINE 89 | EXEC('ALTER DATABASE '+@NEW_DBNAME+' SET ONLINE') 90 | EXEC('ALTER DATABASE '+@NEW_DBNAME+' SET MULTI_USER') -------------------------------------------------------------------------------- /Databases/Databases_ShrinkDatafile.sql: -------------------------------------------------------------------------------- 1 | 2 | --File: Databases/Databases_ShrinkDatafile.sql 3 | --Extracted from https://www.sqlteam.com/forums/topic.asp?TOPIC_ID=80355 4 | --Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 5 | --Added in 2022-01-07 6 | 7 | /* 8 | This script is used to shrink a database file in increments until it reaches a target free space limit. 9 | 10 | Run this script in the database with the file to be shrunk. 11 | 1. Set @DBFileName to the name of database file to shrink. 12 | 2. Set @TargetFreeMB to the desired file free space in MB after shrink. 13 | 3. Set @ShrinkIncrementMB to the increment to shrink file by in MB 14 | 4. Run the script 15 | */ 16 | 17 | declare @DBFileName sysname 18 | declare @TargetFreeMB int 19 | declare @ShrinkIncrementMB int 20 | 21 | -- Set Name of Database file to shrink 22 | set @DBFileName = '' 23 | 24 | -- Set Desired file free space in MB after shrink 25 | set @TargetFreeMB = --ie. 50000 26 | 27 | -- Set Increment to shrink file by in MB 28 | set @ShrinkIncrementMB = --ie. 15120 29 | 30 | -- Show Size, Space Used, Unused Space, and Name of all database files 31 | select [FileSizeMB] = convert(numeric(10,2),round(a.size/128.,2)) 32 | , [UsedSpaceMB] = convert(numeric(10,2),round(fileproperty( a.name,'SpaceUsed')/128.,2)) 33 | , [UnusedSpaceMB] = convert(numeric(10,2),round((a.size-fileproperty( a.name,'SpaceUsed'))/128.,2)) 34 | , [DBFileName] = a.name 35 | from sysfiles a 36 | 37 | declare @sql varchar(8000) 38 | declare @SizeMB int 39 | declare @UsedMB int 40 | 41 | -- Get current file size in MB 42 | select @SizeMB = size/128. from sysfiles where name = @DBFileName 43 | 44 | -- Get current space used in MB 45 | select @UsedMB = fileproperty( @DBFileName,'SpaceUsed')/128. 46 | 47 | select [StartFileSize] = @SizeMB, [StartUsedSpace] = @UsedMB, [DBFileName] = @DBFileName 48 | 49 | -- Loop until file at desired size 50 | while @SizeMB > @UsedMB+@TargetFreeMB+@ShrinkIncrementMB 51 | begin 52 | 53 | set @sql = 54 | 'dbcc shrinkfile ( '+@DBFileName+', '+ 55 | convert(varchar(20),@SizeMB-@ShrinkIncrementMB)+' ) ' 56 | 57 | print 'Start ' + @sql 58 | print 'at '+convert(varchar(30),getdate(),121) 59 | 60 | exec ( @sql ) 61 | 62 | print 'Done ' + @sql 63 | print 'at '+convert(varchar(30),getdate(),121) 64 | 65 | -- Get current file size in MB 66 | select @SizeMB = size/128. from sysfiles where name = @DBFileName 67 | 68 | -- Get current space used in MB 69 | select @UsedMB = fileproperty( @DBFileName,'SpaceUsed')/128. 70 | 71 | select [FileSize] = @SizeMB, [UsedSpace] = @UsedMB, [DBFileName] = @DBFileName 72 | 73 | end 74 | 75 | select [EndFileSize] = @SizeMB, [EndUsedSpace] = @UsedMB, [DBFileName] = @DBFileName 76 | 77 | -- Show Size, Space Used, Unused Space, and Name of all database files 78 | select [FileSizeMB] = convert(numeric(10,2),round(a.size/128.,2)) 79 | , [UsedSpaceMB] = convert(numeric(10,2),round(fileproperty( a.name,'SpaceUsed')/128.,2)) 80 | , [UnusedSpaceMB] = convert(numeric(10,2),round((a.size-fileproperty( a.name,'SpaceUsed'))/128.,2)) 81 | , [DBFileName] = a.name 82 | from sysfiles a 83 | -------------------------------------------------------------------------------- /Deadlocks/Deadlocks_CheckDeadlockNumber.sql: -------------------------------------------------------------------------------- 1 | -- File: DeadLocks_CheckDeadlocksNumber.sql 2 | -- Extracted from "Unkown" 3 | -- Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 4 | -- Added in 2019-09-19 5 | 6 | -- To check the number of deadlocks since last SQL instance reboot 7 | 8 | SELECT 9 |     'Deadlocks Occurrences Report', 10 |     CONVERT(BIGINT,((1.0 * p.cntr_value / 11 | NULLIF(datediff(DD,d.create_date,CURRENT_TIMESTAMP),0)))) as 12 | AveragePerDay, 13 |     CAST(p.cntr_value AS NVARCHAR(100)) + ' deadlocks have been recorded 14 | since startup.' AS Details, 15 |     d.create_date as StartupDateTime 16 | FROM sys.dm_os_performance_counters p 17 | INNER JOIN sys.databases d ON d.name = 'tempdb' 18 | WHERE RTRIM(p.counter_name) = 'Number of Deadlocks/sec' 19 | AND RTRIM(p.instance_name) = '_Total'; -------------------------------------------------------------------------------- /Deadlocks/Deadlocks_CheckDeadlocks.sql: -------------------------------------------------------------------------------- 1 | -- File: DeadLocks_CheckDeadlocks.sql 2 | -- Extracted from "Unkown" 3 | -- Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 4 | -- Added in 2019-09-19 5 | 6 | -- Check Deadlocks using extended-events (system_health default session) 7 | 8 | SELECT 9 | XEvent.value('(@timestamp)[1]', 'datetime') as UTC_event_time, 10 | XEvent.query('(data/value/deadlock)') AS deadlock_graph 11 | FROM ( 12 | SELECT CAST(event_data AS XML) as [target_data] 13 | FROM sys.fn_xe_file_target_read_file('system_health_*.xel',NULL,NULL,NULL) 14 | WHERE object_name like 'xml_deadlock_report' 15 | ) AS [x] 16 | CROSS APPLY target_data.nodes('/event') AS XEventData(XEvent) 17 | 18 | 19 | -- Execute these sentences to active deadlocks traces on SQL log: 20 | -- DBCC TRACEON (1204,-1) 21 | -- DBCC TRACEON (1222,-1) 22 | -- To find the info regarding the deadlocks, check the SQL logs on SSMS or ERRORLOG files. -------------------------------------------------------------------------------- /Files/DropTempdbDatafile.sql: -------------------------------------------------------------------------------- 1 | --File: Files/DropTempdbDatafile.sql 2 | --Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 3 | --Added in 2019-05-23 4 | --Commentaries: remove datafiles from tempdb 5 | 6 | 7 | -- We will have to empty the datafile and then remove it. 8 | 9 | -- Datafile shrink before being able to remove it 10 | USE tempdb; 11 | DBCC SHRINKFILE ('', emptyfile); 12 | 13 | -- Remove tempdb datafile 14 | USE master; 15 | ALTER DATABASE tempdb REMOVE FILE 16 | -------------------------------------------------------------------------------- /Files/ReallocateDBFiles.sql: -------------------------------------------------------------------------------- 1 | --File: Files/ReallocateDBFilessql 2 | --Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 3 | --Added in 2019-05-23 4 | 5 | -- This script will generate the commands to change the current drive (where @DBname dbfiles are allocated) for a new drive. 6 | -- Later you will have to execute the generated scripts 7 | 8 | DECLARE @P1 int; 9 | DECLARE @sql nvarchar(250); 10 | 11 | SET @sql=N'SELECT ''ALTER DATABASE [''+DB_NAME(database_id)+''] MODIFY FILE (NAME=''+name+'', FILENAME=''+@NewDrive+substring(physical_name,2,len(physical_name)-1)+'');'' 12 | FROM sys.master_files 13 | WHERE DB_NAME(database_id)=@DBname'; 14 | 15 | EXEC sp_executesql @sql,N'@DBname nvarchar(128),@newDrive nvarchar(1)', N'', N''; -- replace wiht dbname and newdrive letter 16 | -------------------------------------------------------------------------------- /Indexes/Indexes_BiggestIndexesInDB.sql: -------------------------------------------------------------------------------- 1 | --File: Indexes/Indexes_BiggestIndexesInDB.sql 2 | --Extracted from https://aboutsqlserver.com/2014/12/02/size-does-matter-10-ways-to-reduce-the-database-size-and-improve-performance-in-sql-server/ 3 | --Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 4 | --Added in 2019-04-23 5 | 6 | ;with SpaceInfo(ObjectId, IndexId, TableName, IndexName, Rows, TotalSpaceMB, UsedSpaceMB) 7 | as 8 | ( 9 | select 10 | t.object_id as [ObjectId] 11 | ,i.index_id as [IndexId] 12 | ,s.name + '.' + t.Name as [TableName] 13 | ,i.name as [Index Name] 14 | ,sum(p.[Rows]) as [Rows] 15 | ,sum(au.total_pages) * 8 / 1024 as [Total Space MB] 16 | ,sum(au.used_pages) * 8 / 1024 as [Used Space MB] 17 | from sys.tables t with (nolock) 18 | join sys.schemas s with (nolock) on s.schema_id = t.schema_id 19 | join sys.indexes i with (nolock) on t.object_id = i.object_id 20 | join sys.partitions p with (nolock) on i.object_id = p.object_id and i.index_id = p.index_id 21 | cross apply 22 | ( 23 | select 24 | sum(a.total_pages) as total_pages 25 | ,sum(a.used_pages) as used_pages 26 | from sys.allocation_units a with (nolock) 27 | where p.partition_id = a.container_id 28 | ) au 29 | where i.object_id > 255 30 | group by t.object_id, i.index_id, s.name, t.name, i.name 31 | ) 32 | select 33 | ObjectId, IndexId, TableName, IndexName 34 | ,Rows, TotalSpaceMB, UsedSpaceMB 35 | ,TotalSpaceMB - UsedSpaceMB as [ReservedSpaceMB] 36 | from SpaceInfo 37 | order by TotalSpaceMB desc 38 | option (recompile) -------------------------------------------------------------------------------- /Indexes/Indexes_EnableAllIndexesInADB.sql: -------------------------------------------------------------------------------- 1 | --File: Indexes/Indexes_EnableAllIndexesInADB.sql 2 | --Extracted from https://stackoverflow.com/questions/18236055/disable-and-re-enable-all-indexes-in-a-sql-server-database 3 | --Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 4 | --Added in 2021-08-25 5 | 6 | DECLARE @cmd NVARCHAR(400); 7 | 8 | DECLARE cur_rebuild CURSOR FOR 9 | SELECT 'ALTER INDEX ' + i.name + ' ON ' + SCHEMA_NAME(t.schema_id) + '.' + t.name + ' REBUILD' 10 | FROM sys.indexes i 11 | JOIN sys.tables t ON i.object_id = t.object_id 12 | WHERE i.is_disabled = 1 13 | ORDER BY t.name, i.name; 14 | 15 | OPEN cur_rebuild; 16 | 17 | FETCH NEXT FROM cur_rebuild INTO @cmd; 18 | WHILE @@FETCH_STATUS = 0 19 | BEGIN 20 | EXECUTE sp_executesql @cmd; 21 | FETCH NEXT FROM cur_rebuild INTO @cmd; 22 | END; 23 | 24 | CLOSE cur_rebuild; 25 | DEALLOCATE cur_rebuild; 26 | GO -------------------------------------------------------------------------------- /Indexes/Indexes_FindDisabledIndexes.sql: -------------------------------------------------------------------------------- 1 | --File: Indexes/Indexes_FindDisabledIndexes.sql 2 | --Extracted from https://aboutsqlserver.com/2014/12/02/size-does-matter-10-ways-to-reduce-the-database-size-and-improve-performance-in-sql-server/ 3 | --Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 4 | --Added in 2021-08-20 5 | 6 | select s.name AS schemaName, t.name AS tableName, i.name AS [indexName], i.is_disabled 7 | from sys.tables t 8 | inner join sys.schemas s on t.schema_id = s.schema_id 9 | inner join sys.indexes i on i.object_id = t.object_id 10 | where i.index_id > 0 11 | and i.type in (1, 2) -- clustered & nonclustered only 12 | and i.is_primary_key = 0 -- do not include PK indexes 13 | and i.is_unique_constraint = 0 -- do not include UQ 14 | and i.is_disabled = 1 --remove to find status of all 15 | and i.is_hypothetical = 0 -------------------------------------------------------------------------------- /Indexes/Indexes_IndexFragmentation.sql: -------------------------------------------------------------------------------- 1 | --File: Indexes/Indexes_IndexFragmentation.sql 2 | --Extracted from https://www.sqlshack.com/how-to-identify-and-resolve-sql-server-index-fragmentation/ 3 | --Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 4 | --Added in 2021-09-28 5 | 6 | SELECT S.name as 'Schema', 7 | T.name as 'Table', 8 | I.name as 'Index', 9 | DDIPS.avg_fragmentation_in_percent, 10 | DDIPS.page_count 11 | FROM sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL, NULL, NULL) AS DDIPS 12 | INNER JOIN sys.tables T on T.object_id = DDIPS.object_id 13 | INNER JOIN sys.schemas S on T.schema_id = S.schema_id 14 | INNER JOIN sys.indexes I ON I.object_id = DDIPS.object_id 15 | AND DDIPS.index_id = I.index_id 16 | WHERE DDIPS.database_id = DB_ID() 17 | and I.name is not null 18 | AND DDIPS.avg_fragmentation_in_percent > 0 19 | --AND T.name IN ('') --uncomment to filter by tablename. 20 | ORDER BY DDIPS.avg_fragmentation_in_percent desc 21 | 22 | 23 | -- Another option 24 | 25 | select 26 | index_id, partition_number, alloc_unit_type_desc 27 | ,index_level, page_count, avg_page_space_used_in_percent 28 | from 29 | sys.dm_db_index_physical_stats 30 | ( 31 | db_id() /*Database */ 32 | ,object_id(N'dbo.MyTable') /* Table (Object_ID) */ 33 | ,1 /* Index ID */ 34 | ,null /* Partition ID "NULL" all partitions */ 35 | ,'detailed' /* Mode */ 36 | ) -------------------------------------------------------------------------------- /Indexes/Indexes_IndexesUsageInDB.sql: -------------------------------------------------------------------------------- 1 | --File: Indexes/Indexes_IndexesUsageInDB.sql 2 | --Extracted from https://aboutsqlserver.com/2014/12/02/size-does-matter-10-ways-to-reduce-the-database-size-and-improve-performance-in-sql-server/ 3 | --Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 4 | --Added in 2019-04-23 5 | 6 | select 7 | s.Name + N'.' + t.name as [Table] 8 | ,i.name as [Index] 9 | ,i.is_unique as [IsUnique] 10 | ,ius.user_seeks as [Seeks], ius.user_scans as [Scans] 11 | ,ius.user_lookups as [Lookups] 12 | ,ius.user_seeks + ius.user_scans + ius.user_lookups as [Reads] 13 | ,ius.user_updates as [Updates], ius.last_user_seek as [Last Seek] 14 | ,ius.last_user_scan as [Last Scan], ius.last_user_lookup as [Last Lookup] 15 | ,ius.last_user_update as [Last Update] 16 | from 17 | sys.tables t with (nolock) join sys.indexes i with (nolock) on t.object_id = i.object_id 18 | join sys.schemas s with (nolock) on t.schema_id = s.schema_id 19 | left outer join sys.dm_db_index_usage_stats ius on ius.database_id = db_id() and ius.object_id = i.object_id and ius.index_id = i.index_id 20 | order by s.name, t.name, i.index_id 21 | option (recompile) -------------------------------------------------------------------------------- /Indexes/Indexes_PotentiallyRedundantIndexesInDB.sql: -------------------------------------------------------------------------------- 1 | --File: Indexes/Indexes_PotentiallyRedundantIndexesInDB.sql 2 | --Extracted from https://aboutsqlserver.com/2014/12/02/size-does-matter-10-ways-to-reduce-the-database-size-and-improve-performance-in-sql-server/ 3 | --Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 4 | --Added in 2019-04-23 5 | 6 | select 7 | s.Name + N'.' + t.name as [Table] 8 | ,i1.index_id as [Index1 ID], i1.name as [Index1 Name] 9 | ,dupIdx.index_id as [Index2 ID], dupIdx.name as [Index2 Name] 10 | ,c.name as [Column] 11 | from 12 | sys.tables t join sys.indexes i1 on 13 | t.object_id = i1.object_id 14 | join sys.index_columns ic1 on 15 | ic1.object_id = i1.object_id and 16 | ic1.index_id = i1.index_id and 17 | ic1.index_column_id = 1 18 | join sys.columns c on 19 | c.object_id = ic1.object_id and 20 | c.column_id = ic1.column_id 21 | join sys.schemas s on 22 | t.schema_id = s.schema_id 23 | cross apply 24 | ( 25 | select i2.index_id, i2.name 26 | from 27 | sys.indexes i2 join sys.index_columns ic2 on 28 | ic2.object_id = i2.object_id and 29 | ic2.index_id = i2.index_id and 30 | ic2.index_column_id = 1 31 | where 32 | i2.object_id = i1.object_id and 33 | i2.index_id > i1.index_id and 34 | ic2.column_id = ic1.column_id 35 | ) dupIdx 36 | order by 37 | s.name, t.name, i1.index_id -------------------------------------------------------------------------------- /Infrastructure/Infrasctructure_CheckConnectivity.ps1: -------------------------------------------------------------------------------- 1 | # File: Infrasctructure_CheckConnectivity.ps1 2 | # Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 3 | # Added in 2022-05-13 4 | 5 | #Replaces telnet check in DOS 6 | Test-NetConnection -Port -------------------------------------------------------------------------------- /Infrastructure/Infrastructure_CheckWindowsLicenseStatus.ps1: -------------------------------------------------------------------------------- 1 | # File: Infrastructure_CheckWindowsLicenseStatus.ps1 2 | # Extracted from Unkonwn 3 | # Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 4 | # Added in 2019-11-07 5 | 6 | #defined initial data 7 | $LicenseStatus = @("Unlicensed","Licensed","OOB Grace","OOT Grace","Non-Genuine Grace","Notification","Extended Grace") 8 | 9 | $ComputerName = @() 10 | $ComputerName += '' 11 | $ComputerName += '' 12 | # … 13 | 14 | Foreach($CN in $ComputerName) { 15 | try { 16 | Get-CimInstance -ClassName SoftwareLicensingProduct -ComputerName $CN | ` 17 | Where-Object {$_.PartialProductKey -and $_.Name -like "*Windows*"} | ` 18 | Select-Object ` 19 | @{Expression={$_.PSComputerName}; Name="ComputerName"},` 20 | @{Expression={$_.Name}; Name="WindowsName"}, ` 21 | ApplicationID, ` 22 | @{Expression={$LicenseStatus[$($_.LicenseStatus)]}; Name="LicenseStatus"} 23 | } catch { 24 | Wrhite-Host "Error checking $CN server ($_.Exception.ItemName): $_.Exception.Message" 25 | } 26 | } -------------------------------------------------------------------------------- /Infrastructure/Wintel_CheckIPs.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/beumof/SQL-Server-Admin-scripts/2f672e1e93b71771b814c7a1e96883abd9a39d9a/Infrastructure/Wintel_CheckIPs.ps1 -------------------------------------------------------------------------------- /Infrastructure/Wintel_CheckMountpoints.ps1: -------------------------------------------------------------------------------- 1 | # File: Wintel_CheckMountpoints.ps1 2 | # Based on https://learn-powershell.net/2012/08/10/locating-mount-points-using-powershell/ 3 | # Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 4 | # Added in 2020-07-02 5 | 6 | Get-WmiObject Win32_Volume -Filter "DriveType='3'" | ForEach-Object { 7 | New-Object PSObject -Property @{ 8 | Name = $_.Name 9 | Label = $_.Label 10 | FreeSpace_GB = ([Math]::Round($_.FreeSpace /1GB,2)) 11 | TotalSize_GB = ([Math]::Round($_.Capacity /1GB,2)) 12 | } 13 | } | Select-Object Name, Label, TotalSize_GB, FreeSpace_GB | Sort-Object -Property Name -------------------------------------------------------------------------------- /Infrastructure/Wintel_Drives_CheckBytesPerCluster.ps1: -------------------------------------------------------------------------------- 1 | Get-WmiObject -Class Win32_Volume -Filter "DriveType = '3'" | Select-Object DriveLetter, Label, BlockSize -------------------------------------------------------------------------------- /Infrastructure/Wintel_Drives_DriveSizes.ps1: -------------------------------------------------------------------------------- 1 | # File: Wintel_CheckDrives.ps1 2 | # Extracted from https://mcpmag.com/articles/2018/01/26/view-drive-information-with-powershell.aspx 3 | # Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 4 | # Added in 2019-09-27 5 | 6 | Get-WmiObject -Class Win32_logicaldisk -Filter "DriveType = '3'" | 7 | Select-Object DeviceID, @{L="CapacityGB";E={"{0:N2}" -f ($_.Size/1GB)}}, @{L='FreeSpaceGB';E={"{0:N2}" -f ($_.FreeSpace /1GB)}} | Format-Table -------------------------------------------------------------------------------- /Infrastructure/Wintel_GetLast10ServerReboots.ps1: -------------------------------------------------------------------------------- 1 | Get-Eventlog system | Where-Object {$_.eventid -eq 6006} | Select-Object -first 10 2 | 3 | #For more details 4 | 5 | Get-Eventlog system | Where-Object {$_.eventid -eq 1074 -or $_.eventid -eq 6008 -or $_.eventid -eq 1076} ` 6 | | FormatTable Machinename, TimeWritten, UserName, EventID, Message -AutoSize -Wrap -------------------------------------------------------------------------------- /Infrastructure/Wintel_GetListApplications.ps1: -------------------------------------------------------------------------------- 1 | # File: Wintel_GetListApplications.ps1 2 | # Extracted from https://www.howtogeek.com/165293/how-to-get-a-list-of-software-installed-on-your-pc-with-a-single-command/#:~:text=First%2C%20open%20PowerShell%20by%20clicking,with%20an%20empty%20PowerShell%20prompt.&text=PowerShell%20will%20give%20you%20a,the%20date%20you%20installed%20it. 3 | # Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 4 | # Added in 2020-11-24_2 5 | 6 | Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | 7 | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate | Format-Table –AutoSize -------------------------------------------------------------------------------- /Memory/Memory_ReleaseSQLMemoryInUse.sql: -------------------------------------------------------------------------------- 1 | --File: Memory_ReleaseSQLMemoryInUse.sql 2 | --Extracted from: https://stackoverflow.com/questions/38998909/how-do-you-force-sql-server-to-release-memory 3 | --Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 4 | --Added in 2021-12-16 5 | 6 | sp_configure 'show advanced options', 1; 7 | GO 8 | RECONFIGURE; 9 | GO 10 | /*** Drop the max down to XX GB temporarily ***/ 11 | sp_configure 'max server memory', 49152; --48GB 12 | GO 13 | RECONFIGURE; 14 | GO 15 | /**** Wait a couple minutes to let SQLServer to naturally release the RAM..... ****/ 16 | WAITFOR DELAY '00:02:00'; 17 | GO 18 | /** now bump it back up to "lots of RAM"! ****/ 19 | sp_configure 'max server memory', 50068; 20 | GO 21 | RECONFIGURE; 22 | GO 23 | sp_configure 'show advanced options', 0; 24 | GO 25 | RECONFIGURE; 26 | GO -------------------------------------------------------------------------------- /Migrations/FixOrphans.sql: -------------------------------------------------------------------------------- 1 | --File: Migraations/Migrations_FixOrphans.sql 2 | --Extracted from: Unknown (updated with info from MS SQL official web) 3 | --Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 4 | --Added in 2019-10-14 5 | 6 | SELECT 'ALTER USER ['+[name]+'] WITH LOGIN = ['+[name]+']' 7 | FROM sysusers 8 | WHERE sid IS NOT NULL 9 | AND [name] NOT IN ('dbo','guest','public') 10 | AND [name] NOT LIKE 'db_%' 11 | AND [name] NOT LIKE 'BUILTIN%' 12 | 13 | 14 | /* Old version, it creates the login if it does not exist, but sp will be deprecated 15 | -- EXEC master..sp_change_users_login 'report' -- list users to fix 16 | 17 | SELECT 'EXEC master..sp_change_users_login ''auto_fix'','''+[name]+'''' 18 | FROM sysusers 19 | WHERE sid IS NOT NULL 20 | AND [name] NOT IN ('dbo','guest','public') 21 | AND [name] NOT LIKE 'db_%' 22 | AND [name] NOT LIKE 'BUILTIN%' 23 | 24 | */ -------------------------------------------------------------------------------- /Migrations/Migrations_CompareDBs.sql: -------------------------------------------------------------------------------- 1 | --File: Migrations_CompareDBs.sql 2 | --Extracted from: Unknown (updated with info from MS SQL official web. 3 | --Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 4 | --Added in 2019-05-02 5 | 6 | 7 | --USE [DB] --Used for automatizations 8 | 9 | SELECT 10 | 'Count' = COUNT(*) 11 | , 'Type' = CASE type 12 | WHEN 'AF' THEN 'Aggregate function (CLR)' 13 | WHEN 'C' THEN 'CHECK constraint' 14 | WHEN 'D' THEN 'Default or DEFAULT constraint' 15 | WHEN 'F' THEN 'FOREIGN KEY constraint' 16 | WHEN 'FN' THEN 'Scalar function' 17 | WHEN 'FS' THEN 'Assembly (CLR) scalar-function' 18 | WHEN 'FT' THEN 'Assembly (CLR) table-valued function' 19 | WHEN 'IF' THEN 'In-lined table-function' 20 | WHEN 'IT' THEN 'Internal table' 21 | WHEN 'K' THEN 'PRIMARY KEY or UNIQUE constraints' 22 | WHEN 'L' THEN 'Log' 23 | WHEN 'P' THEN 'Stored procedure' 24 | WHEN 'PC' THEN 'Assembly (CLR) stored-procedure' 25 | WHEN 'PK' THEN 'PRIMARY KEY constraint (type is K)' 26 | WHEN 'R' THEN 'Rule' 27 | WHEN 'RF' THEN 'Replication filter stored procedure' 28 | WHEN 'S' THEN 'System table' 29 | WHEN 'SN' THEN 'Synonym' 30 | WHEN 'SQ' THEN 'Service queue' 31 | WHEN 'TA' THEN 'Assembly (CLR) DML trigger' 32 | WHEN 'TF' THEN 'Table function' 33 | WHEN 'TR' THEN 'SQL DML Trigger' 34 | WHEN 'TT' THEN 'Table type' 35 | WHEN 'U' THEN 'User table' 36 | WHEN 'UQ' THEN 'UNIQUE constraint (type is K)' 37 | WHEN 'V' THEN 'View' 38 | WHEN 'X' THEN 'Extended stored procedure' 39 | ELSE TYPE 40 | END 41 | , GETDATE() as 'Date' 42 | FROM sysobjects 43 | GROUP BY type 44 | ORDER BY type 45 | GO -------------------------------------------------------------------------------- /Partitioning/Partitioning_ListPartitions.sql: -------------------------------------------------------------------------------- 1 | --File: Partitioning/Partitioning_ListPartitions.sql 2 | --Extracted from https://littlekendra.com/2017/01/31/which-filegroup-is-that-partition-using-how-many-rows-does-it-have/ 3 | --Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 4 | --Added in 2019-08-09 5 | 6 | SELECT 7 | sc.name + N'.' + so.name as [Schema.Table], 8 | si.index_id as [Index ID], 9 | si.type_desc as [Structure], 10 | si.name as [Index], 11 | stat.row_count AS [Rows], 12 | stat.in_row_reserved_page_count * 8./1024./1024. as [In-Row GB], 13 | stat.lob_reserved_page_count * 8./1024./1024. as [LOB GB], 14 | p.partition_number AS [Partition #], 15 | pf.name as [Partition Function], 16 | CASE pf.boundary_value_on_right 17 | WHEN 1 then 'Right / Lower' 18 | ELSE 'Left / Upper' 19 | END as [Boundary Type], 20 | prv.value as [Boundary Point], 21 | fg.name as [Filegroup] 22 | FROM sys.partition_functions AS pf 23 | JOIN sys.partition_schemes as ps on ps.function_id=pf.function_id 24 | JOIN sys.indexes as si on si.data_space_id=ps.data_space_id 25 | JOIN sys.objects as so on si.object_id = so.object_id 26 | JOIN sys.schemas as sc on so.schema_id = sc.schema_id 27 | JOIN sys.partitions as p on 28 | si.object_id=p.object_id 29 | and si.index_id=p.index_id 30 | LEFT JOIN sys.partition_range_values as prv on prv.function_id=pf.function_id 31 | and p.partition_number= 32 | CASE pf.boundary_value_on_right WHEN 1 33 | THEN prv.boundary_id + 1 34 | ELSE prv.boundary_id 35 | END 36 | /* For left-based functions, partition_number = boundary_id, 37 | for right-based functions we need to add 1 */ 38 | JOIN sys.dm_db_partition_stats as stat on stat.object_id=p.object_id 39 | and stat.index_id=p.index_id 40 | and stat.index_id=p.index_id and stat.partition_id=p.partition_id 41 | and stat.partition_number=p.partition_number 42 | JOIN sys.allocation_units as au on au.container_id = p.hobt_id 43 | and au.type_desc ='IN_ROW_DATA' 44 | /* Avoiding double rows for columnstore indexes. */ 45 | /* We can pick up LOB page count from partition_stats */ 46 | JOIN sys.filegroups as fg on fg.data_space_id = au.data_space_id 47 | ORDER BY [Schema.Table], [Index ID], [Partition Function], [Partition #]; 48 | GO -------------------------------------------------------------------------------- /Performance/Performance_ActiveTransactions.sql: -------------------------------------------------------------------------------- 1 | --File: Performance/Performance_ActiveTrasactions.sql 2 | --Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 3 | --Added in 2021-10-01 4 | 5 | /* Este script obtiene las transacciones activas en el servidor e información sobre las mismas: 6 | - Cuando comenzó la transacción 7 | - La sesión y login de quién lo ejecuta, el hostname desde dónde llega la petición y la aplicación cliente desde dónde llega la petición 8 | - La query/procedure que se ejecuta en la request actual de la transacción 9 | - La cantidad (En MBs) de Log que está usando la transacción, como el numero de registros que lleva modificados. 10 | - WARNING! En caso de transacciones "huerfanas" o de "irse al cafe" no aparecerán aquí, las transacciones abiertas pero sin nada en ejecución se ven en la tabla dm_tran_database_transactions pero no tienen registro asignado en la tabla dm_exec_requests (Estos casos de transacciones "de café" serían relevantes como causa de que el Log no se trunque con los backups o en casos de Bloqueos) 11 | */ 12 | 13 | select database_transaction_begin_time as BeginTime 14 | , r.session_id, s.login_name AS Login 15 | , text 16 | , DB_NAME(tr.database_id) as DatabaseName 17 | , s.HOST_NAME as HostName 18 | , s.program_name as ClientApp 19 | , tr.transaction_id 20 | , database_transaction_log_bytes_used/1024/1024 as TlogMBsUsed 21 | , database_transaction_log_bytes_reserved/1024/1024 as TlogMBsReserved 22 | , database_transaction_log_record_count 23 | , database_transaction_state 24 | , database_transaction_status 25 | , database_transaction_log_bytes_used_system 26 | , database_transaction_log_bytes_reserved_system 27 | from sys.dm_tran_database_transactions tr 28 | inner join sys.dm_exec_requests r on tr.transaction_id = r.transaction_id 29 | inner join sys.dm_exec_sessions s on r.session_id = s.session_id 30 | cross apply sys.dm_exec_sql_text(sql_handle) 31 | where r.session_id != @@SPID -- to exclude our session from the results. 32 | --AND database_transaction_log_bytes_used > 100*1024*1024 --To show transactions just bigger than 100 MB -------------------------------------------------------------------------------- /Performance/Performance_BlockedProcesses.sql: -------------------------------------------------------------------------------- 1 | --File: Performance/Performance_BlockedProcesses.sql 2 | --Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 3 | --Added in 2021-10-01 4 | 5 | CREATE TABLE #sp_who2 (SPID INT,Status VARCHAR(255), 6 | Login VARCHAR(255),HostName VARCHAR(255), 7 | BlkBy VARCHAR(255),DBName VARCHAR(255), 8 | Command VARCHAR(255),CPUTime INT, 9 | DiskIO INT,LastBatch VARCHAR(255), 10 | ProgramName VARCHAR(255),SPID2 INT, 11 | REQUESTID INT) 12 | 13 | INSERT INTO #sp_who2 EXEC sp_who2 14 | 15 | --FIND BLOCKED PROCESSES (IGNORING PARALLELSIM) 16 | SELECT * 17 | FROM #sp_who2 18 | WHERE BlkBy<>' .' AND SPID<>BlkBy 19 | ORDER BY SPID ASC 20 | 21 | --FIND HEAD LOCKERS 22 | SELECT * 23 | FROM #sp_who2 24 | WHERE SPID IN (SELECT BlkBy FROM #sp_who2 WHERE BlkBy<>' .' AND SPID<>BlkBy GROUP BY BlkBy) 25 | AND blkBy=' .' 26 | 27 | DROP TABLE #sp_who2 -------------------------------------------------------------------------------- /Performance/Performance_BufferPoll.sql: -------------------------------------------------------------------------------- 1 | --File: Performance/Performance_BufferPool.sql 2 | --Extracted from https://www.sqlskills.com/blogs/paul/inside-the-storage-engine-whats-in-the-buffer-pool/ 3 | --Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 4 | --Added in 2021-01-28 5 | 6 | SELECT ObjectName 7 | ,ISNULL(Clean,0) AS CleanPages 8 | ,ISNULL(Dirty,0) AS DirtyPages 9 | ,STR(ISNULL(Clean,0)/128.0,12,2) AS CleanPagesMB 10 | ,STR(ISNULL(Dirty,0/128.0),12,2) AS DirtyPagesMB 11 | FROM ( 12 | SELECT CASE WHEN GROUPING(t.object_id) = 1 THEN '=> Sum' ELSE Quotename(OBJECT_SCHEMA_NAME(t.object_id)) + '.' + Quotename(OBJECT_NAME(t.object_id)) END AS ObjectName 13 | ,CASE WHEN bd.is_modified = 1 THEN 'Dirty' ELSE 'Clean' END AS 'PageState' ,COUNT (*) AS 'PageCount' 14 | FROM sys.dm_os_buffer_descriptors bd 15 | INNER JOIN sys.allocation_units AS allc ON allc.allocation_unit_id = bd.allocation_unit_id 16 | INNER JOIN sys.partitions part ON allc.container_id = part.partition_id 17 | INNER JOIN sys.tables t ON part.object_id = t.object_id 18 | WHERE bd.database_id = DB_ID() 19 | GROUP BY GROUPING sets ((t.object_id,bd.is_modified),(bd.is_modified)) 20 | )pgs PIVOT (SUM(PageCount) FOR PageState IN ([Clean],[Dirty])) AS pvt -------------------------------------------------------------------------------- /Performance/Performance_CachePlans.sql: -------------------------------------------------------------------------------- 1 | --File: Performance/Performance_CachePlans.sql 2 | --Extracted from https://www.sqlskills.com/blogs/kimberly/plan-cache-and-optimizing-for-adhoc-workloads/ 3 | --Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 4 | --Added in 2021-01-28 5 | 6 | SELECT objtype AS [CacheType], 7 | COUNT_BIG(*) AS [Total Plans], 8 | SUM(CAST(size_in_bytes AS DECIMAL(18, 2))) / 1024 / 1024 AS [Total MBs], 9 | AVG(usecounts) AS [Avg Use Count], 10 | SUM(CAST((CASE WHEN usecounts = 1 THEN size_in_bytes ELSE 0 END) AS DECIMAL(18, 2))) / 1024 / 1024 AS [Total MBs – USE Count 1], 11 | SUM(CASE WHEN usecounts = 1 THEN 1 ELSE 0 END) AS [Total Plans – USE Count 1] 12 | FROM sys.dm_exec_cached_plans 13 | GROUP BY objtype 14 | ORDER BY [Total MBs – USE Count 1] DESC; 15 | 16 | -- To clear plan cache (ad-hoc): DBCC FREESYSTEMCACHE ('SQL Plans') -------------------------------------------------------------------------------- /Performance/Performance_CurrentMemoryUsageByDB.sql: -------------------------------------------------------------------------------- 1 | --File: Performance/Performance_CurrentMemoryUsageByDB.sql 2 | --Provided by P. Dominguez 3 | --Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 4 | --Added in 2022-05-13 5 | 6 | WITH MemoryGrants (DBName, MBGrants) AS ( 7 | SELECT DB_NAME(s.database_id) AS DBName 8 | ,SUM(mg.requested_memory_kb/1024) AS MBGrants 9 | FROM sys.dm_exec_query_memory_grants mg 10 | INNER JOIN sys.dm_exec_sessions s ON mg.session_id = s.session_id 11 | GROUP BY DB_NAME(s.database_id) 12 | ), MemoryBuffer (DBName, MBBuffer) AS ( 13 | SELECT DB_NAME(database_id) as DBName 14 | ,COUNT(1) * 8 / 1024 AS MBBuffer 15 | FROM sys.dm_os_buffer_descriptors 16 | GROUP BY database_id 17 | ) SELECT SYSDATETIMEOFFSET() 18 | ,mbf.DBName 19 | ,MBBuffer 20 | ,COALESCE(MBGrants,0) AS MBGrants 21 | ,MBBuffer + COALESCE(MBGrants,0) AS MBTotal 22 | FROM MemoryBuffer mbf 23 | LEFT JOIN MemoryGrants mgf ON mbf.DBName = mgf.DBName -------------------------------------------------------------------------------- /Performance/Performance_Emulation_sp_who2.sql: -------------------------------------------------------------------------------- 1 | --File: Performance/Performance_Emulation_sp_who2.sql 2 | --Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 3 | --Added in 2021-10-01 4 | 5 | 6 | CREATE TABLE #sp_who2 (SPID INT,Status VARCHAR(255), 7 | Login VARCHAR(255),HostName VARCHAR(255), 8 | BlkBy VARCHAR(255),DBName VARCHAR(255), 9 | Command VARCHAR(255),CPUTime INT, 10 | DiskIO INT,LastBatch VARCHAR(255), 11 | ProgramName VARCHAR(255),SPID2 INT, 12 | REQUESTID INT) 13 | 14 | INSERT INTO #sp_who2 EXEC sp_who2 15 | 16 | SELECT * 17 | FROM #sp_who2 18 | WHERE 1=1 19 | --AND DBName NOT IN ('master','msdb','model','tempdb') 20 | --AND SPID<>@@SPID --To exclude current connection 21 | ORDER BY SPID ASC 22 | 23 | DROP TABLE #sp_who2 -------------------------------------------------------------------------------- /Performance/Performance_FindLargeTransactions.sql: -------------------------------------------------------------------------------- 1 | --File: Performance/Performance_FindLargeTransactions.sql 2 | --Extracted from https://techcommunity.microsoft.com/t5/sql-server-support/finding-large-transactions-that-bloat-your-transaction-log/ba-p/333999 3 | --Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 4 | --Added in 2021-01-20 5 | 6 | set nocount on 7 | go 8 | declare @datetime datetime 9 | select @datetime = GETDATE() 10 | select @datetime logtime, text, tr.database_id, tr.transaction_id, database_transaction_log_bytes_used, database_transaction_log_bytes_reserved, 11 | database_transaction_log_record_count, database_transaction_state, database_transaction_status, 12 | database_transaction_log_bytes_used_system, database_transaction_log_bytes_reserved_system 13 | from sys.dm_tran_database_transactions tr 14 | inner join sys.dm_exec_requests r 15 | on tr.transaction_id = r.transaction_id 16 | cross apply sys.dm_exec_sql_text(sql_handle) 17 | where database_transaction_log_bytes_used > 100*1024*1024 -- 100 MB -------------------------------------------------------------------------------- /Processes/SQLProcesses_ActiveProcesses+QueryPlan.sql: -------------------------------------------------------------------------------- 1 | --SQL Server active processes (including query plan) 2 | SELECT 3 | r.session_id 4 | ,st.TEXT AS batch_text 5 | ,SUBSTRING(st.TEXT, statement_start_offset / 2 + 1, ( 6 | ( 7 | CASE 8 | WHEN r.statement_end_offset = - 1 9 | THEN (LEN(CONVERT(NVARCHAR(max), st.TEXT)) * 2) 10 | ELSE r.statement_end_offset 11 | END 12 | ) - r.statement_start_offset 13 | ) / 2 + 1) AS statement_text 14 | ,qp.query_plan AS 'XML Plan' 15 | ,r.* 16 | FROM sys.dm_exec_requests r 17 | CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) AS st 18 | CROSS APPLY sys.dm_exec_query_plan(r.plan_handle) AS qp 19 | ORDER BY cpu_time DESC -------------------------------------------------------------------------------- /Processes/SQLProcesses_ActiveProcesses.sql: -------------------------------------------------------------------------------- 1 | --SQL Server active processes 2 | SELECT s.session_id, 3 | r.status, 4 | r.blocking_session_id 'Blk by', 5 | r.wait_type, 6 | wait_resource, 7 | r.wait_time / (1000 * 60) 'Wait M', 8 | r.cpu_time, 9 | r.logical_reads, 10 | r.reads, 11 | r.writes, 12 | r.total_elapsed_time / (1000 * 60) 'Elaps M', 13 | Substring(st.TEXT,(r.statement_start_offset / 2) + 1, 14 | ((CASE r.statement_end_offset 15 | WHEN -1 16 | THEN Datalength(st.TEXT) 17 | ELSE r.statement_end_offset 18 | END - r.statement_start_offset) / 2) + 1) AS statement_text, 19 | Coalesce(Quotename(Db_name(st.dbid)) + N'.' + Quotename(Object_schema_name(st.objectid, st.dbid)) + N'.' + 20 | Quotename(Object_name(st.objectid, st.dbid)), '') AS command_text, 21 | r.command, 22 | s.login_name, 23 | s.host_name, 24 | s.program_name, 25 | s.last_request_end_time, 26 | s.login_time, 27 | r.open_transaction_count 28 | FROM sys.dm_exec_sessions AS s 29 | JOIN sys.dm_exec_requests AS r 30 | ON r.session_id = s.session_id 31 | CROSS APPLY sys.Dm_exec_sql_text(r.sql_handle) AS st 32 | WHERE r.session_id != @@SPID 33 | ORDER BY r.cpu_time desc -------------------------------------------------------------------------------- /Processes/SQLProcesses_BadSessions.sql: -------------------------------------------------------------------------------- 1 | --File: Processes/SQLProcesses_BadSessions.sql 2 | --Compilled in https://www.dbrnd.com/2017/02/sql-server-script-to-find-bad-sessions-or-processes-block-transaction-waiting-session/ 3 | --Added in 2019-06-26 4 | --Commentaries: Check worst performance connections 5 | 6 | SELECT TOP 25 7 | spid 8 | ,blocked 9 | ,convert(varchar(10),db_name(dbid)) as DBName 10 | ,cpu 11 | ,datediff(second,login_time, getdate()) as Secs 12 | ,convert(float, cpu / datediff(second,login_time, getdate())) as PScore 13 | ,convert(varchar(16), hostname) as Host 14 | ,convert(varchar(50), program_name) as Program 15 | ,convert(varchar(20), loginame) as Login 16 | FROM master..sysprocesses 17 | WHERE datediff(second,login_time, getdate()) > 0 and spid > 50 18 | ORDER BY pscore desc 19 | -------------------------------------------------------------------------------- /Processes/SQLProcesses_KillAllDBProcesses.sql: -------------------------------------------------------------------------------- 1 | --File: Processes\SQLProcesses_KillAllDBProcesses.sql 2 | --Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 3 | --Added in 2019-12-17 4 | --Commentaries: Kill all processes related to a DB. Useful when locking other tasks. BEWARE. 5 | 6 | DECLARE @dbname sysname 7 | SET @dbname = '' 8 | 9 | DECLARE @spid int 10 | SELECT @spid = MIN(spid) FROM master.dbo.sysprocesses WHERE dbid = DB_ID(@dbname) 11 | 12 | WHILE @spid IS NOT NULL 13 | BEGIN 14 | EXECUTE ('KILL ' + @spid) 15 | SELECT @spid = min(spid) FROM master.dbo.sysprocesses WHERE dbid = DB_ID(@dbname) AND spid > @spid 16 | END -------------------------------------------------------------------------------- /Processes/SQLProcesses_MostCPUbyHandle.sql: -------------------------------------------------------------------------------- 1 | -- Get most CPU usage by plan handle 2 | select top 50 3 | sum(qs.total_worker_time) as total_cpu_time, 4 | sum(qs.execution_count) as total_execution_count, 5 | count(*) as number_of_statements, 6 | qs.plan_handle 7 | from 8 | sys.dm_exec_query_stats qs 9 | group by qs.plan_handle 10 | order by sum(qs.total_worker_time) desc -------------------------------------------------------------------------------- /Processes/SQLProcesses_ProgramStatistics.sql: -------------------------------------------------------------------------------- 1 | --File: Processes/SQLProcesses_BadSessions.sql 2 | --Compilled in https://www.dbrnd.com/2017/02/sql-server-script-to-find-open-connections-and-cpu-usage-of-each-connected-client-programs/ 3 | --Added in 2019-06-26 4 | --Commentaries: Check Client program open connections and CPU Stats. 5 | 6 | 7 | SELECT 8 | convert(varchar(50), program_name) as ProgramName 9 | ,count(*) as TotalInstances 10 | ,sum(cpu) as CPUSum 11 | ,sum(datediff(second, login_time, getdate())) as SumOfSecond 12 | ,convert(float, sum(cpu)) / convert(float, sum(datediff(second, login_time, getdate()))) as PerformanceScore 13 | ,convert(float, sum(cpu)) / convert(float, sum(datediff(second, login_time, getdate()))) / count(*) as ProgramPerformance 14 | FROM master..sysprocesses 15 | WHERE spid > 50 16 | GROUP BY 17 | convert(varchar(50), program_name) 18 | ORDER BY PerformanceScore DESC 19 | -------------------------------------------------------------------------------- /Processes/SQLProcesses_SQLPercentage.sql: -------------------------------------------------------------------------------- 1 | --SQL Server process usage in the last 15 minutes 2 | DECLARE @ms_ticks_now BIGINT 3 | SELECT @ms_ticks_now = ms_ticks 4 | FROM sys.dm_os_sys_info; 5 | SELECT TOP 15 record_id 6 | ,dateadd(ms, - 1 * (@ms_ticks_now - [timestamp]), GetDate()) AS EventTime 7 | ,SQLProcessUtilization 8 | ,SystemIdle 9 | ,100 - SystemIdle - SQLProcessUtilization AS OtherProcessUtilization 10 | FROM ( 11 | SELECT record.value('(./Record/@id)[1]', 'int') AS record_id 12 | ,record.value('(./Record/SchedulerMonitorEvent/SystemHealth/SystemIdle)[1]', 'int') AS SystemIdle 13 | ,record.value('(./Record/SchedulerMonitorEvent/SystemHealth/ProcessUtilization)[1]', 'int') AS SQLProcessUtilization 14 | ,TIMESTAMP 15 | FROM ( 16 | SELECT TIMESTAMP 17 | ,convert(XML, record) AS record 18 | FROM sys.dm_os_ring_buffers 19 | WHERE ring_buffer_type = N'RING_BUFFER_SCHEDULER_MONITOR' 20 | AND record LIKE '%%' 21 | ) AS x 22 | ) AS y 23 | ORDER BY record_id DESC -------------------------------------------------------------------------------- /QEP_AlreadyRunningProcesses.sql: -------------------------------------------------------------------------------- 1 | --SQL Server active processes (including query plan) 2 | SELECT 3 | r.session_id 4 | ,st.TEXT AS batch_text 5 | ,SUBSTRING(st.TEXT, statement_start_offset / 2 + 1, ( 6 | ( 7 | CASE 8 | WHEN r.statement_end_offset = - 1 9 | THEN (LEN(CONVERT(NVARCHAR(max), st.TEXT)) * 2) 10 | ELSE r.statement_end_offset 11 | END 12 | ) - r.statement_start_offset 13 | ) / 2 + 1) AS statement_text 14 | ,qp.query_plan AS 'XML Plan' 15 | ,r.* 16 | FROM sys.dm_exec_requests r 17 | CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) AS st 18 | CROSS APPLY sys.dm_exec_query_plan(r.plan_handle) AS qp 19 | ORDER BY cpu_time DESC -------------------------------------------------------------------------------- /QEP_EstimatedExecutionPlans.sql: -------------------------------------------------------------------------------- 1 | --Get estimated Execution plans 2 | SELECT UseCounts, Cacheobjtype, Objtype, TEXT, query_plan 3 | FROM sys.dm_exec_cached_plans 4 | CROSS APPLY sys.dm_exec_sql_text(plan_handle) 5 | CROSS APPLY sys.dm_exec_query_plan(plan_handle) -------------------------------------------------------------------------------- /Queries_Top10HeavyQueries.sql: -------------------------------------------------------------------------------- 1 | --SELECT TOP 10 HEAVY QUERIES (SQL 2005-...) 2 | --CLASIFIED BY CPU-I/O-READ/WRITE 3 | SELECT TOP 10 SUBSTRING(qt.TEXT, (qs.statement_start_offset/2)+1, 4 | ((CASE qs.statement_end_offset 5 | WHEN -1 THEN DATALENGTH(qt.TEXT) 6 | ELSE qs.statement_end_offset 7 | END - qs.statement_start_offset)/2)+1), 8 | qs.execution_count, 9 | qs.total_logical_reads, qs.last_logical_reads, 10 | qs.total_logical_writes, qs.last_logical_writes, 11 | qs.total_worker_time, 12 | qs.last_worker_time, 13 | qs.total_elapsed_time/1000000 total_elapsed_time_in_S, 14 | qs.last_elapsed_time/1000000 last_elapsed_time_in_S, 15 | qs.last_execution_time, 16 | qp.query_plan 17 | FROM sys.dm_exec_query_stats qs 18 | CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) qt 19 | CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) qp 20 | ORDER BY qs.total_logical_reads DESC -- logical reads 21 | -- ORDER BY qs.total_logical_writes DESC -- logical writes 22 | -- ORDER BY qs.total_worker_time DESC -- CPU time 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## SQL-Server-Admin-scripts 2 | 3 | Compilation of Scripts (mostly SQL ones) used to administer SQL Server 4 | 5 | Please check also the [wiki](https://github.com/beumof/SQL-Server-Admin-scripts/wiki) as it's a guide to administer SQL Server. 6 | -------------------------------------------------------------------------------- /Replications/Replications_Status.sql: -------------------------------------------------------------------------------- 1 | --File: Replications/Replications_Status.sql 2 | --Extracted from https://basitaalishan.com/2012/07/25/transact-sql-script-to-monitor-replication-status/ 3 | --Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 4 | --Added in 2021-01-08 5 | 6 | USE [distribution] 7 | 8 | IF OBJECT_ID('Tempdb.dbo.#ReplStats') IS NOT NULL 9 | DROP TABLE #ReplStats 10 | 11 | CREATE TABLE [dbo].[#ReplStats] ( 12 | [DistributionAgentName] [nvarchar](100) NOT NULL 13 | ,[DistributionAgentStartTime] [datetime] NOT NULL 14 | ,[DistributionAgentRunningDurationInSeconds] [int] NOT NULL 15 | ,[IsAgentRunning] [bit] NULL 16 | ,[ReplicationStatus] [varchar](14) NULL 17 | ,[LastSynchronized] [datetime] NOT NULL 18 | ,[Comments] [nvarchar](max) NOT NULL 19 | ,[Publisher] [sysname] NOT NULL 20 | ,[PublicationName] [sysname] NOT NULL 21 | ,[PublisherDB] [sysname] NOT NULL 22 | ,[Subscriber] [nvarchar](128) NULL 23 | ,[SubscriberDB] [sysname] NULL 24 | ,[SubscriptionType] [varchar](64) NULL 25 | ,[DistributionDB] [sysname] NULL 26 | ,[Article] [sysname] NOT NULL 27 | ,[UndelivCmdsInDistDB] [int] NULL 28 | ,[DelivCmdsInDistDB] [int] NULL 29 | ,[CurrentSessionDeliveryRate] [float] NOT NULL 30 | ,[CurrentSessionDeliveryLatency] [int] NOT NULL 31 | ,[TotalTransactionsDeliveredInCurrentSession] [int] NOT NULL 32 | ,[TotalCommandsDeliveredInCurrentSession] [int] NOT NULL 33 | ,[AverageCommandsDeliveredInCurrentSession] [int] NOT NULL 34 | ,[DeliveryRate] [float] NOT NULL 35 | ,[DeliveryLatency] [int] NOT NULL 36 | ,[TotalCommandsDeliveredSinceSubscriptionSetup] [int] NOT NULL 37 | ,[SequenceNumber] [varbinary](16) NULL 38 | ,[LastDistributerSync] [datetime] NULL 39 | ,[Retention] [int] NULL 40 | ,[WorstLatency] [int] NULL 41 | ,[BestLatency] [int] NULL 42 | ,[AverageLatency] [int] NULL 43 | ,[CurrentLatency] [int] NULL 44 | ) ON [PRIMARY] 45 | 46 | INSERT INTO #ReplStats 47 | SELECT da.[name] AS [DistributionAgentName] 48 | ,dh.[start_time] AS [DistributionAgentStartTime] 49 | ,dh.[duration] AS [DistributionAgentRunningDurationInSeconds] 50 | ,md.[isagentrunningnow] AS [IsAgentRunning] 51 | ,CASE md.[status] 52 | WHEN 1 53 | THEN '1 - Started' 54 | WHEN 2 55 | THEN '2 - Succeeded' 56 | WHEN 3 57 | THEN '3 - InProgress' 58 | WHEN 4 59 | THEN '4 - Idle' 60 | WHEN 5 61 | THEN '5 - Retrying' 62 | WHEN 6 63 | THEN '6 - Failed' 64 | END AS [ReplicationStatus] 65 | ,dh.[time] AS [LastSynchronized] 66 | ,dh.[comments] AS [Comments] 67 | ,md.[publisher] AS [Publisher] 68 | ,da.[publication] AS [PublicationName] 69 | ,da.[publisher_db] AS [PublisherDB] 70 | ,CASE 71 | WHEN da.[anonymous_subid] IS NOT NULL 72 | THEN UPPER(da.[subscriber_name]) 73 | ELSE UPPER(s.[name]) 74 | END AS [Subscriber] 75 | ,da.[subscriber_db] AS [SubscriberDB] 76 | ,CASE da.[subscription_type] 77 | WHEN '0' 78 | THEN 'Push' 79 | WHEN '1' 80 | THEN 'Pull' 81 | WHEN '2' 82 | THEN 'Anonymous' 83 | ELSE CAST(da.[subscription_type] AS [varchar](64)) 84 | END AS [SubscriptionType] 85 | ,md.[distdb] AS [DistributionDB] 86 | ,ma.[article] AS [Article] 87 | ,ds.[UndelivCmdsInDistDB] 88 | ,ds.[DelivCmdsInDistDB] 89 | ,dh.[current_delivery_rate] AS [CurrentSessionDeliveryRate] 90 | ,dh.[current_delivery_latency] AS [CurrentSessionDeliveryLatency] 91 | ,dh.[delivered_transactions] AS [TotalTransactionsDeliveredInCurrentSession] 92 | ,dh.[delivered_commands] AS [TotalCommandsDeliveredInCurrentSession] 93 | ,dh.[average_commands] AS [AverageCommandsDeliveredInCurrentSession] 94 | ,dh.[delivery_rate] AS [DeliveryRate] 95 | ,dh.[delivery_latency] AS [DeliveryLatency] 96 | ,dh.[total_delivered_commands] AS [TotalCommandsDeliveredSinceSubscriptionSetup] 97 | ,dh.[xact_seqno] AS [SequenceNumber] 98 | ,md.[last_distsync] AS [LastDistributerSync] 99 | ,md.[retention] AS [Retention] 100 | ,md.[worst_latency] AS [WorstLatency] 101 | ,md.[best_latency] AS [BestLatency] 102 | ,md.[avg_latency] AS [AverageLatency] 103 | ,md.[cur_latency] AS [CurrentLatency] 104 | FROM [distribution]..[MSdistribution_status] ds 105 | INNER JOIN [distribution]..[MSdistribution_agents] da ON da.[id] = ds.[agent_id] 106 | INNER JOIN [distribution]..[MSArticles] ma ON ma.publisher_id = da.publisher_id 107 | AND ma.[article_id] = ds.[article_id] 108 | INNER JOIN [distribution]..[MSreplication_monitordata] md ON [md].[job_id] = da.[job_id] 109 | INNER JOIN [distribution]..[MSdistribution_history] dh ON [dh].[agent_id] = md.[agent_id] 110 | AND md.[agent_type] = 3 111 | INNER JOIN [master].[sys].[servers] s ON s.[server_id] = da.[subscriber_id] 112 | --Created WHEN your publication has the immediate_sync property set to true. This property dictates 113 | --whether snapshot is available all the time for new subscriptions to be initialized. 114 | --This affects the cleanup behavior of transactional replication. If this property is set to true, 115 | --the transactions will be retained for max retention period instead of it getting cleaned up 116 | --as soon as all the subscriptions got the change. 117 | WHERE da.[subscriber_db] <> 'virtual' 118 | AND da.[anonymous_subid] IS NULL 119 | AND dh.[start_time] = ( 120 | SELECT TOP 1 start_time 121 | FROM [distribution]..[MSdistribution_history] a 122 | INNER JOIN [distribution]..[MSdistribution_agents] b ON a.[agent_id] = b.[id] 123 | AND b.[subscriber_db] <> 'virtual' 124 | WHERE [runstatus] <> 1 125 | ORDER BY [start_time] DESC 126 | ) 127 | AND dh.[runstatus] <> 1 128 | 129 | SELECT 'Transactional Replication Summary' AS [Comments]; 130 | 131 | SELECT [DistributionAgentName] 132 | ,[DistributionAgentStartTime] 133 | ,[DistributionAgentRunningDurationInSeconds] 134 | ,[IsAgentRunning] 135 | ,[ReplicationStatus] 136 | ,[LastSynchronized] 137 | ,[Comments] 138 | ,[Publisher] 139 | ,[PublicationName] 140 | ,[PublisherDB] 141 | ,[Subscriber] 142 | ,[SubscriberDB] 143 | ,[SubscriptionType] 144 | ,[DistributionDB] 145 | ,SUM([UndelivCmdsInDistDB]) AS [UndelivCmdsInDistDB] 146 | ,SUM([DelivCmdsInDistDB]) AS [DelivCmdsInDistDB] 147 | ,[CurrentSessionDeliveryRate] 148 | ,[CurrentSessionDeliveryLatency] 149 | ,[TotalTransactionsDeliveredInCurrentSession] 150 | ,[TotalCommandsDeliveredInCurrentSession] 151 | ,[AverageCommandsDeliveredInCurrentSession] 152 | ,[DeliveryRate] 153 | ,[DeliveryLatency] 154 | ,[TotalCommandsDeliveredSinceSubscriptionSetup] 155 | ,[SequenceNumber] 156 | ,[LastDistributerSync] 157 | ,[Retention] 158 | ,[WorstLatency] 159 | ,[BestLatency] 160 | ,[AverageLatency] 161 | ,[CurrentLatency] 162 | FROM #ReplStats 163 | GROUP BY [DistributionAgentName] 164 | ,[DistributionAgentStartTime] 165 | ,[DistributionAgentRunningDurationInSeconds] 166 | ,[IsAgentRunning] 167 | ,[ReplicationStatus] 168 | ,[LastSynchronized] 169 | ,[Comments] 170 | ,[Publisher] 171 | ,[PublicationName] 172 | ,[PublisherDB] 173 | ,[Subscriber] 174 | ,[SubscriberDB] 175 | ,[SubscriptionType] 176 | ,[DistributionDB] 177 | ,[CurrentSessionDeliveryRate] 178 | ,[CurrentSessionDeliveryLatency] 179 | ,[TotalTransactionsDeliveredInCurrentSession] 180 | ,[TotalCommandsDeliveredInCurrentSession] 181 | ,[AverageCommandsDeliveredInCurrentSession] 182 | ,[DeliveryRate] 183 | ,[DeliveryLatency] 184 | ,[TotalCommandsDeliveredSinceSubscriptionSetup] 185 | ,[SequenceNumber] 186 | ,[LastDistributerSync] 187 | ,[Retention] 188 | ,[WorstLatency] 189 | ,[BestLatency] 190 | ,[AverageLatency] 191 | ,[CurrentLatency] 192 | 193 | SELECT 'Transactional Replication Summary Details' AS [Comments]; 194 | 195 | SELECT [Publisher] 196 | ,[PublicationName] 197 | ,[PublisherDB] 198 | ,[Article] 199 | ,[Subscriber] 200 | ,[SubscriberDB] 201 | ,[SubscriptionType] 202 | ,[DistributionDB] 203 | ,SUM([UndelivCmdsInDistDB]) AS [UndelivCmdsInDistDB] 204 | ,SUM([DelivCmdsInDistDB]) AS [DelivCmdsInDistDB] 205 | FROM #ReplStats 206 | GROUP BY [Publisher] 207 | ,[PublicationName] 208 | ,[PublisherDB] 209 | ,[Article] 210 | ,[Subscriber] 211 | ,[SubscriberDB] 212 | ,[SubscriptionType] 213 | ,[DistributionDB] -------------------------------------------------------------------------------- /SPs/SPs_RecompileSP.sql: -------------------------------------------------------------------------------- 1 | --File: SPs/SPs_RecompileSP.sql 2 | --Extracted from https://www.sqlservercentral.com/forums/topic/finding-last-date-compiled-for-a-stored-procedure 3 | --Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 4 | --Added in 2021-09-24 5 | 6 | EXEC sp_recompile ''; 7 | 8 | --To confirm the recompliation 9 | 10 | SELECT 11 | db_name(database_id) as database_name 12 | ,object_name(object_id) as sp_name 13 | ,cached_time 14 | ,last_execution_time 15 | FROM sys.dm_exec_procedure_stats 16 | WHERE database_id = db_id('') 17 | --AND object_name(object_id)='' --Uncomment to filter by the SPName -------------------------------------------------------------------------------- /SQLJobs/SQLJobs_CheckJobHistory.sql: -------------------------------------------------------------------------------- 1 | --File: SQLJobs\SQLJobs_CheckJobHistory 2 | --Adadted from https://www.mssqltips.com/sqlservertip/2850/querying-sql-server-agent-job-history-data/ 3 | --Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 4 | --Added in 2020-01-02 5 | --Commentaries: Check job history, or even failures 6 | 7 | SELECT 8 | j.name AS 'JobName' 9 | ,msdb.dbo.agent_datetime(run_date, run_time) AS 'RunDateTime' 10 | ,(run_duration/10000*3600 + (run_duration/100)%100*60 + run_duration%100 + 31 ) AS 'RunDurationSeconds' 11 | ,run_status 12 | FROM msdb.dbo.sysjobs j 13 | INNER JOIN msdb.dbo.sysjobhistory h ON j.job_id = h.job_id 14 | WHERE j.enabled = 1 -- only Enabled Jobs 15 | -- AND j.name = 'Checklogspace' -- uncomment to search for a particular job 16 | -- AND msdb.dbo.agent_datetime(run_date, run_time) BETWEEN '12/08/2012' AND '12/10/2012' -- uncomment for date range queries 17 | -- AND run_status = 0 -- uncomment to check for job failures 18 | ORDER BY RunDateTime DESC -------------------------------------------------------------------------------- /SQLJobs/SQLJobs_CheckSQLJobsRunning.sql: -------------------------------------------------------------------------------- 1 | --File: SQLJobs\SQLJobs_CheckSQLJobsRunning.sql 2 | --Adadted from https://social.msdn.microsoft.com/Forums/sqlserver/en-US/0eb9c96c-fc06-4ae6-8b30-4e486d62f573/how-to-retrieve-current-step-name-of-currently-running-job?forum=transactsql 3 | -- & https://www.dbrnd.com/2017/02/sql-server-script-to-find-bad-sessions-or-processes-block-transaction-waiting-session/ 4 | --Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 5 | --Added in 2019-11-12 6 | --Commentaries: Check SQL jobs running in the SQL instance (with SPID) 7 | 8 | SELECT 9 | distinct j.name as JobName 10 | , spid 11 | , js.step_id as StepId 12 | , CASE WHEN ja.last_executed_step_id IS NULL THEN js.step_name ELSE js2.step_name END as StepName 13 | , ja.start_execution_date as StartDateTime 14 | , 'Running' AS RunStatus 15 | , (SELECT RIGHT('0' + CONVERT(VARCHAR(2), DATEDIFF(second, start_execution_date, GetDate())/3600), 2) 16 | + ':' + RIGHT('0' + CONVERT(VARCHAR(2), DATEDIFF(second, start_execution_date, GetDate())%3600/60), 2) 17 | + ':' + RIGHT('0' + CONVERT(VARCHAR(2), DATEDIFF(second, start_execution_date, GetDate())%60), 2) ) as Duration 18 | , program_name 19 | FROM msdb.dbo.sysjobactivity ja 20 | JOIN msdb.dbo.sysjobs j ON ja.job_id = j.job_id 21 | LEFT JOIN msdb.dbo.sysjobsteps js ON j.job_id = js.job_id 22 | AND CASE WHEN ja.last_executed_step_id IS NULL THEN j.start_step_id ELSE ja.last_executed_step_id END = js.step_id 23 | LEFT JOIN msdb.dbo.sysjobsteps js2 ON js.job_id = js2.job_id AND js.on_success_step_id = js2.step_id 24 | LEFT JOIN master.dbo.sysprocesses sp ON master.dbo.fn_varbintohexstr(convert(varbinary(16), j.job_id)) COLLATE Latin1_General_CI_AI = substring(replace(program_name, 'SQLAgent - TSQL JobStep (Job ', ''), 1, 34) 25 | WHERE ja.session_id = ( SELECT TOP 1 session_id FROM msdb.dbo.syssessions ORDER BY agent_start_date DESC ) 26 | AND start_execution_date IS NOT NULL 27 | AND stop_execution_date IS NULL 28 | 29 | -------------------------------------------------------------------------------- /SQLJobs/SQLJobs_EnableAgentXPs.sql: -------------------------------------------------------------------------------- 1 | --File: SQLJobs/SQLJobs_EnableAgentXPs.sql 2 | --Extracted from https://www.sqlshack.com/how-to-fix-the-agent-xps-disabled-error/ 3 | --Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 4 | --Added in 2021-10-21 5 | 6 | use master 7 | go 8 | exec sp_configure 'Show advanced options',1 9 | Go 10 | reconfigure with override 11 | go 12 | 13 | use master 14 | go 15 | exec sp_configure 'Agent XPs',1 16 | Go 17 | reconfigure with override 18 | go 19 | 20 | use master 21 | go 22 | exec sp_configure 'Show advanced options',0 23 | Go 24 | reconfigure with override 25 | go 26 | 27 | --To check it, value field should be 1. 28 | use master 29 | go 30 | select * from sys.configurations where name='Agent XPs' -------------------------------------------------------------------------------- /SSIS/SSIS_WhichJobExecutedaPackage.sql: -------------------------------------------------------------------------------- 1 | --File: SSIS\WhichJobExecutedaPackage.sql 2 | --Extracted from https://www.mssqltips.com/sqlservertip/2561/querying-sql-server-agent-job-information/ 3 | --Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 4 | --Added in 2019-10-15 5 | 6 | SELECT 7 | [sJOB].[job_id] AS [JobID] 8 | , [sJOB].[name] AS [JobName] 9 | , [sJSTP].[step_uid] AS [StepID] 10 | , [sJSTP].[step_id] AS [StepNo] 11 | , [sJSTP].[step_name] AS [StepName] 12 | , CASE [sJSTP].[subsystem] 13 | WHEN 'ActiveScripting' THEN 'ActiveX Script' 14 | WHEN 'CmdExec' THEN 'Operating system (CmdExec)' 15 | WHEN 'PowerShell' THEN 'PowerShell' 16 | WHEN 'Distribution' THEN 'Replication Distributor' 17 | WHEN 'Merge' THEN 'Replication Merge' 18 | WHEN 'QueueReader' THEN 'Replication Queue Reader' 19 | WHEN 'Snapshot' THEN 'Replication Snapshot' 20 | WHEN 'LogReader' THEN 'Replication Transaction-Log Reader' 21 | WHEN 'ANALYSISCOMMAND' THEN 'SQL Server Analysis Services Command' 22 | WHEN 'ANALYSISQUERY' THEN 'SQL Server Analysis Services Query' 23 | WHEN 'SSIS' THEN 'SQL Server Integration Services Package' 24 | WHEN 'TSQL' THEN 'Transact-SQL script (T-SQL)' 25 | ELSE sJSTP.subsystem 26 | END AS [StepType] 27 | , [sPROX].[name] AS [RunAs] 28 | , [sJSTP].[database_name] AS [Database] 29 | , [sJSTP].[command] AS [ExecutableCommand] 30 | , CASE [sJSTP].[on_success_action] 31 | WHEN 1 THEN 'Quit the job reporting success' 32 | WHEN 2 THEN 'Quit the job reporting failure' 33 | WHEN 3 THEN 'Go to the next step' 34 | WHEN 4 THEN 'Go to Step: ' 35 | + QUOTENAME(CAST([sJSTP].[on_success_step_id] AS VARCHAR(3))) 36 | + ' ' 37 | + [sOSSTP].[step_name] 38 | END AS [OnSuccessAction] 39 | , [sJSTP].[retry_attempts] AS [RetryAttempts] 40 | , [sJSTP].[retry_interval] AS [RetryInterval (Minutes)] 41 | , CASE [sJSTP].[on_fail_action] 42 | WHEN 1 THEN 'Quit the job reporting success' 43 | WHEN 2 THEN 'Quit the job reporting failure' 44 | WHEN 3 THEN 'Go to the next step' 45 | WHEN 4 THEN 'Go to Step: ' 46 | + QUOTENAME(CAST([sJSTP].[on_fail_step_id] AS VARCHAR(3))) 47 | + ' ' 48 | + [sOFSTP].[step_name] 49 | END AS [OnFailureAction] 50 | FROM 51 | [msdb].[dbo].[sysjobsteps] AS [sJSTP] 52 | INNER JOIN [msdb].[dbo].[sysjobs] AS [sJOB] ON [sJSTP].[job_id] = [sJOB].[job_id] 53 | LEFT JOIN [msdb].[dbo].[sysjobsteps] AS [sOSSTP] ON [sJSTP].[job_id] = [sOSSTP].[job_id] 54 | AND [sJSTP].[on_success_step_id] = [sOSSTP].[step_id] 55 | LEFT JOIN [msdb].[dbo].[sysjobsteps] AS [sOFSTP] ON [sJSTP].[job_id] = [sOFSTP].[job_id] 56 | AND [sJSTP].[on_fail_step_id] = [sOFSTP].[step_id] 57 | LEFT JOIN [msdb].[dbo].[sysproxies] AS [sPROX] ON [sJSTP].[proxy_id] = [sPROX].[proxy_id] 58 | WHERE [sJSTP].[subsystem] = 'SSIS' -- Change or comment this line to check job steps in general. 59 | ORDER BY [JobName], [StepNo] -------------------------------------------------------------------------------- /Snippets/Snippet_CursorSnippet.sql: -------------------------------------------------------------------------------- 1 | --File: Snippets/Snippet_CursorSnippets.sql 2 | --Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 3 | --Added in 2021-12-02 4 | 5 | DECLARE cCursor CURSOR 6 | FOR SELECT * FROM TableName 7 | 8 | DECLARE @variable type; 9 | 10 | OPEN cCursor 11 | FETCH NEXT FROM cCursor INTO @variable; 12 | WHILE @@FETCH_STATUS = 0 13 | BEGIN 14 | FETCH NEXT FROM cCursor INTO @variable; 15 | END 16 | CLOSE cCursor; 17 | DEALLOCATE cCursor; -------------------------------------------------------------------------------- /Snippets/Snippet_SQLDateTimeSnippets.sql: -------------------------------------------------------------------------------- 1 | --File: Snippets/Snippet_SQLDateTimeSnippets.sql 2 | --Compilled in https://github.com/beumof/SQL-Server-Admin-scripts 3 | --Added in 2021-01-27 4 | 5 | -- Get Date_Time formated. IE: 20210127_102157 6 | SELECT CONVERT(VARCHAR(20),GETDATE(),112) + '_' + REPLACE(CONVERT(VARCHAR(20),GETDATE(),108),':','') 7 | 8 | -- To generate job log with __