├── ##040.Set model FileGrowth 256MB.sql ├── ##070.sp__DBAdmin_Startup.sql ├── 010.Job.msdb DB Backup History Cleanup.sql ├── 010.add_database_mail_acct.sql ├── 010.fn_ConvertSecsToFormattedTime.sql ├── 010.pr_RebuildIndexes.sql ├── 010.tbl CHECKDB_Parms.sql ├── 020.Alert.Add trans log backup as response.sql ├── 020.Job.Reindexing.sql ├── 020.add_operator.sql ├── 020.fn_DatabaseDetails.sql ├── 020.tbl CHECKDB_Schedule.sql ├── 030.add_alerts.sql ├── 030.fn_CheckDB_ScheduleDay.sql ├── 030.pr_SetCmdShell.sql ├── 035.add_mirror_alerts.sql ├── 040.pr_ExecSQLCmd.sql ├── 040.pr_Set_CheckDB_Schedule.sql ├── 050.Add SysAdmin Users.sql ├── 050.pr_CheckDB_Processing.sql ├── 050.pr_DeleteFiles.sql ├── 060.Enable SQL Agent Mail Profile.sql ├── 060.Job.DBAdmin CHECKDB Processing.sql ├── 080.Job.DBAdmin Failure Test.sql ├── 090.sp_getRunningJobs.sql ├── 1 Create AuditLog Table for DDL.sql ├── 1 Disable Jobs.sql ├── 2 Create Server DDL Audit Trigger.sql ├── 2 Stop Running Jobs and Log the Step executing.sql ├── 20170228-sp_sqlskills_exposecolsinindexlevels.sql ├── 20170228-sp_sqlskills_helpindex.sql ├── 3 Create Database DDL Audit Trigger.sql ├── 3 Start Jobs at the step where they were stopped.sql ├── 4 Enable Jobs Which Were Disabled.sql ├── AA Install SQL from Command Line.txt ├── AA Install SQL from Command Line2.txt ├── AD Access Identification.sql ├── ADMIN - SQL Server Service Restart Send Email.sql ├── ActiveXESessions_SystemHealthInfo_Ch06_ExpandingTheToolset.sql ├── Add Email Notification For Failed SQL Server Agent Jobs.sql ├── Add Gmail as Database Mail Account.sql ├── Add Linked Server.sql ├── Add New Tempdb Files.sql ├── Add SQL Agent Operate and Assign it to All Jobs for Failure.sql ├── Add User to Azure Database and Add Role Membership.sql ├── AllDeadLockScripts_Ch08_Deadlocks.sql ├── Alter Database Logical File Names.sql ├── Attach DB File Without Log File.sql ├── Attach database using Create Database.sql ├── Audit Login Events.sql ├── Azure Handy T-SQL.sql ├── Azure SQL Database Resoruce Metrics.sql ├── AzureSQLdatabase_UpdateFirewallRule.sql ├── AzureSQLdatabase_UpdateFirewallRule_2.sql ├── Azure_Database_Firewall_Script.sql ├── Azure_Delete_Unattached_Managed_Disks.ps1 ├── Azure_Firewall_Script.sql ├── BCP Out Sample.sql ├── BCP out and in dynamic statement.sql ├── Backup File CleanUp.sql ├── Backup Tlog files Using Powershell.txt ├── Backup database.sql ├── BackupTDE.sql ├── Blocking.sql ├── Bruins_ClientDW_WhoIsActive.ps1 ├── Build Comma Seperated Column and Query.sql ├── CDCScripts_Ch10_ChangeDataCapture.sql ├── CPU counts.sql ├── Cached Exec Plan Query.sql ├── Calculate Median Value.sql ├── CalculateAllSQLServerPerformanceCounterValues_Ch05_sys.dm_os_performance_countersHowtoReadCalculate .sql ├── CalculateCumulativeWaitTimesByWaitType_Chap03_SlowPerformance.sql ├── CaptureCfgChangesUsingDefaultTrace_Ch10_DefaultTrace.sql ├── Check Azure SQL DB User Role and Role Permissions.sql ├── Check Database Mail Configuration.sql ├── Check Free Space And Truncate.sql ├── Check If The Latest Backup File Exist.sql ├── Check SQL Server Replication Jobs.sql ├── CheckPoint Free Proc Cache Clean Buffers.sql ├── Clean up Replication.sql ├── Collect Index Usage Statistics.sql ├── Collect Job Report From SQL Servers.sql ├── Comma Seperate Mutiple Rows.sql ├── CompareResourceWaitsVsSignalWaits_Chap03_SignalWaits.sql ├── Compress Table.sql ├── Configure Database Mail.sql ├── Configure Distribution First Time.sql ├── Convert Int to Time Function.sql ├── Create Azure SQL Server And Azure SQL Database From Template Copy.txt ├── Create Azure SQL Server And Azure SQL Database From Template.ps1 ├── Create Credential and SSIS Proxy.sql ├── Create Database Mail Account And Profile.sql ├── Create Database Mail Profile and Account.sql ├── Create Database With Multiple File Groups.sql ├── Create Dynamic Database SnapShot Daily.sql ├── Create Dynamic Database SnapShot In Minutes.sql ├── Create Extended Event Session 24HourDataCapture.sql ├── Create Function DelimitedSplit8K For Splitting Comma Sepeprated Parameters.sql ├── Create Function to Parse String.sql ├── Create Linked Server to Azure Database.sql ├── Create New DBA Operator.sql ├── Create ProcExec Role and Grant Execution Select on Objects.sql ├── Create Proxy for PowerShell.sql ├── Create Random Password.sql ├── Create SQL Login With SID.sql ├── Create SQL Server Alerts.sql ├── Create SSIS Proxy Account.sql ├── Create Tally Table.sql ├── Create User for Azure SQL Database.sql ├── Create or Drop All PKs.sql ├── Create ssb_azure_dba for Azure SQL Database.sql ├── CreateAgentAlerts_Ch08_CreateANewAlert.sql ├── CreateCustomDataCollectionScriptForQueryStats_Ch07_DefiningCustomDataCollection.sql ├── CreateCustomIndexUsageCollector_Ch07_DefiningCustomDataCollection.sql ├── CreateDDLTriggerForServerDatabaseEvent_Ch10_DDLTriggers.sql ├── CreateDECODE_TLOGScripts_Ch10_ReadingTheTransactionLog.sql ├── CreateHistoricalWaitStatsTable_Ch07_RollingYourOwn.sql ├── CreateMonitoredWaitTypesTable_Ch07_RollingYourOwn.sql ├── CreateSQLAuditsAndServerDatabaseSpecifications_Ch10_SQLAudit.sql ├── CreateStoredProc_usp_DailyWaitStats_Ch07_RollingYourOwn.sql ├── Create_Pool_Disks.ps1 ├── Create_StorageAccount_Container_SAS_Credential.ps1 ├── Create_red-gate_monitor_user.sql ├── DBA Backup System Databases Script.sql ├── DBA Backup System Databases To Data Domain.sql ├── DBA Backup System Databases.sql ├── DBA Backup User Databases To Data Domain.sql ├── DBA Backup User Databases.sql ├── DBA Check Identity Value Table.sql ├── DBA Check Identity Values for All Tables.sql ├── DBA Check MSDB Suspect_Pages.sql ├── DBA Check Mail Sytem.sql ├── DBA Clean up MSDB Backup Tables.txt ├── DBA Clean up MSDB Mail log and Backup History New.sql ├── DBA Clean up MSDB Mail log and Backup History Newest.sql ├── DBA Clean up MSDB Mail log and Backup History.sql ├── DBA Clean up MSDB Mail logs.sql ├── DBA Cleanup Old Backup Files Using PowerShell.sql ├── DBA Collect Index Daily Usage Statistics.sql ├── DBA Create Severity Alerts.sql ├── DBA Cycle SQL Server Error Log.sql ├── DBA DBCC for all databases.sql ├── DBA Daily Backup Report.sql ├── DBA Delete Differential Backups.sql ├── DBA Delete Old MSDB Backup History.sql ├── DBA Delete System Database Backup Files.sql ├── DBA Delete User Database Backup Files.sql ├── DBA Operator.sql ├── DBA Rebuild Reorganize Indexes on All Databases.sql ├── DBA Restore TLog Files (Log Shipping).sql ├── DBA SQL Server Services Started.sql ├── DBA Send Email For SQL Services Restart.sql ├── DBA Send Job Disabled Alert.sql ├── DBA Update Statistics.sql ├── DBA WaitStat Collection 1 Tables.sql ├── DBA WaitStat Collection 2 Create Jobs.sql ├── DBA WaitStat Collection 3 Create Jobs.sql ├── DBA Weekly Backup Report.sql ├── DBCC CheckDB for All DBs.sql ├── DBCC PAGE sample.sql ├── DMV Starter Pack.sql ├── DataCollectorCounterDataDetailsQuery_Ch05_DataCollector.sql ├── Database IO Report.sql ├── DatabaseBackup.sql ├── DatabaseIntegrityCheck.sql ├── Days Since the Job Run.sql ├── DefaultTemplate.xaml ├── DefaultTraceQueries&Activity_Ch05_DefaultTrace.sql ├── Delete Duplicate Rows With CTE.sql ├── Delete Old backups.txt ├── DeleteAllDataInDB.sql ├── Deploy all sys2 dmvs (1).sql ├── Deploy all sys2 dmvs.sql ├── DesignQueryForCustomReportWaitStats_Ch08_CreateTheDataSets.sql ├── DetermineIndexCostBenefits.sql ├── Disable Enable FK.sql ├── Disable Publishing Distribution.sql ├── DriveFreeSpace.sql ├── Drop Clean Buffers and Free Proc Cache.sql ├── Drop FK Constraint.sql ├── Drop Procs Functions Schemas.sql ├── Drop Restored Copy of Replicated Database.sql ├── Drop Server Name and Add Builtin Admin Group To SysAdmin.sql ├── Drop Views and Tables.sql ├── DropConstraintDynamic.sql ├── DropCopyandCreatSubscription.sql ├── DumpTopWaitsToHistoryWaitsTable_Chap03_SlowPerformance.sql ├── Dynamic Database Restore.sql ├── Dynamic Drop and Create FK statement.sql ├── Dynamic Restore with Case From Linked Server.sql ├── Dynamic Restore with Case.sql ├── Dynamic Stored Procedure Where Clause.sql ├── Dynamically Restore Multi File DB backup.sql ├── EmailModel_TableChanges_ForAzureSQL.sql ├── Enable Query Store.sql ├── Estimate Compression Savings.sql ├── FK Create Statement Execute From Stored Table.sql ├── FK Create Statement Store To Table.sql ├── FK Drop Statement Execute From Stored Table.sql ├── FK Drop Statement Store To Table.sql ├── Find Active Cluster Node.sql ├── Find Active Directory Users and Groups.sql ├── Find Active Sessions.sql ├── Find Active Transactions and Execution Plans.sql ├── Find Actively Running SQL Server Agent Jobs.sql ├── Find Ad Hoc Related Plan Cache numbers.sql ├── Find All Objects in All User Databases Using Name Like.sql ├── Find All The Schemas Tables Columns and DataTypes.sql ├── Find All User Created Objects.sql ├── Find Authentication Scheme And Net Transport.sql ├── Find Availability Group Health Secondary Node.sql ├── Find Avg Space Used Page Count and Avg Record Size Per Index For Table.sql ├── Find Batch Requests Compilations and Plan ReUse.sql ├── Find Block Size of the Volumes.sql ├── Find Buffer Descriptors what's in SQL Server buffer.sql ├── Find Buffer Pool Cache Size For Each Db.sql ├── Find Buffer Usage For Each Database.sql ├── Find CPU Intensive Queries.sql ├── Find Cached Plans and SQL.sql ├── Find Cached Temporary Object Count.sql ├── Find Column Exist in Multiple Tables.sql ├── Find Column Names and Data Types.sql ├── Find Columns With Constraints And Defaults.sql ├── Find Compressed Indexes For The Object.sql ├── Find Compressed Indexes.sql ├── Find Compressed Objects in SQL 2008.sql ├── Find Compression Info For All Indexes In A Database.sql ├── Find Connection Info to SQL Server.sql ├── Find Count of Connections To SQL Server.sql ├── Find Data Size And Log Size And Percent Log Used For All DBs.sql ├── Find Database Backup Size In GB.sql ├── Find Database File Growth Settings.sql ├── Find Database File space and File Group Info For All Databases.sql ├── Find Database File space and File Group Info.sql ├── Find Database Mail Profile and Account Info.sql ├── Find Database Role Permissions.sql ├── Find Database Role Permissions2.sql ├── Find Database Size for All Databases.sql ├── Find Date of the Sunday Week Day.sql ├── Find Degree of Selectivity.sql ├── Find Deprecated Features Being Used.sql ├── Find Detailed Information on Existing Indexes.sql ├── Find Detailed Information on Missing Indexes.sql ├── Find Detailed Information on Unused Indexes.sql ├── Find Duplicate and Overlapping Indexes.sql ├── Find Estimated Compression and Compress Table.sql ├── Find Estimated Compressions For All Tables.sql ├── Find Estimated Cost Of Execution Plan.sql ├── Find Execution Plan And Plan Handle with Usage Count.sql ├── Find Execution Plan Cache Usage For Stored Procs.sql ├── Find Execution Plan Cache Usage.sql ├── Find Execution Plan For Cached Object.sql ├── Find Execution Plan for Cached Queries.sql ├── Find Execution Plan for Parallel Executed Cached Queries.sql ├── Find Execution Plans Using Specific Index.sql ├── Find FK Constraints.sql ├── Find FKs to Table.sql ├── Find File Size and Available Space for Database.sql ├── Find File Size and File Group Info for All Online Database.sql ├── Find First and Last Day of The month.sql ├── Find Foreign Key Parent Chilld Indexing.sql ├── Find Foreign Keys Existing and Maybe Missing.sql ├── Find Free Drive Space.sql ├── Find Free Space in DB Files.sql ├── Find Full Text Indexes in a Database.sql ├── Find General Info for All Databases.sql ├── Find Heap Tables.sql ├── Find ID Gap In A Table.sql ├── Find Index Column info.sql ├── Find Index Key Space Usage.sql ├── Find Index Leaf Page Insert Update Delete Count.sql ├── Find Index Size and Stats For All Indexes.sql ├── Find Index Stats Date For All Tables.sql ├── Find Index Stats Date For Single Table.sql ├── Find Index Usage Statistics.sql ├── Find Index Usage and Recommended Missing Indexes.sql ├── Find Index dept and Page Count for Each Level of index.sql ├── Find Orphan Users In Each User Database.sql ├── Find SQL Server Agent Job Execution Information.sql ├── Find SQL Server Agent Job Schedule Information.sql ├── Find SQL Server Agent Job Setup and Configuration Information.sql ├── Find SQL Server Agent Job Steps Execution Information.sql ├── Find SQL Server Agent Job Steps Setup and Configuration Information.sql ├── Find SQL Server Agent Job in Detail.sql ├── Find Transactional Replication @Schema_Option.sql ├── Find all DMVs.sql ├── Find execution plan handle and remove it from plan cache.sql ├── Find if column has Default.sql ├── FindDupIdx_Ch04_DuplicateIndexes.sql ├── FindLogFileSizeChangeDates.sql ├── FormatXMLoutput_sp_diagnostics_Ch06_The_sp_diagnostics_procedure_XQuery.sql ├── GetAvgTaskCountsTotal_Chap03_RunnableTaskCount.sql ├── GetBufferHitCacheRatio_Ch05_sys.dm_os_performance_countersHowtoReadCalculate .sql ├── GetFillFactorForAllIndexesOnDatabase_Chap04_FillFactor.sql ├── GetHistoricalCPUUtilizationSQLvsOtherProcesses_Chap03_CPUBlameGame.sql ├── GetIODiskLatenciesReadWrite_PaulRandal_Chap03_IOMayBeWhyYourServerIsSlow.sql ├── GetIODiskLatencyPercentageByIOStallsByDatabase_Chap03_IOMayBeWhyYourServerIsSlow.sql ├── GetIODiskUsagePercentageByDatabase_Chap03_IOMayBeWhyYourServerIsSlow.sql ├── GetIODiskUsagePercentageByDriveLetter_Chap03_IOMayBeWhyYourServerIsSlow.sql ├── GetIdealMemUsagePercentTotalAndTargetMemory_Chap03_FindAllCurrentlyBlockedRequests.sql ├── GetIdealMemUsagePercentTotalAndTargetMemory_Chap03_MemoryPressure.sql ├── GetIndexUsageSimple_Chap04_CommonIndexIssues_IndexUsage.sql ├── GetMissingIdxCreate_Chap04_MissingIndexes.sql ├── GetPendingIORequests_Chap03_IOMayBeWhyYourServerIsSlow.sql ├── GetPendingMemoryGrantsWithQueries_Chap03_MemoryPressure.sql ├── GetRawPerfCounterValuesTotalAndTargetMemory_Chap03_MemoryPressure.sql ├── GetSQLServerEngineProperties_Inventories_Chap02.sql ├── GetSingletonLookupCount_Chap04_CommonIndexIssues_IndexUsage.sql ├── GetTop20TotalQueryResponseTimeForIndividualQueries_Chap03_SlowPerformance.sql ├── GetTopSQLServerWaits_Chap03_ObservingWaitStatistics.sql ├── GetTotalServerQueryResponseTime_Chap03_SlowPerformance.sql ├── GetTtlPlanCacheReUse_Chap03_AnatomyCPUMetadataQuery .sql ├── GetWhatSQLServerIsWtgOnNow_Chap03_AnatomyCPUMetadataQuery.sql ├── Get_List_of_dbroles.sql ├── Get_sys.dm_os_performance_counters_DMV_Chap03_IntroWaits&Queues.sql ├── IO Related Queries.sql ├── IOstalls and PageIOLatch.sql ├── Identify Database Role Membership for MS Shipped Roles.sql ├── Identify Server Role Membership.sql ├── IdentifyQueriesCausingCPUPressure_Chap03_AnatomyCPUMetadataQuery .sql ├── IdentityValueReport.sql ├── Import Results to SQL Server.txt ├── IndexOptimize.sql ├── Index_Usage_Stats_Ch07_DefiningCustomDataCollection.sql ├── Investigate_Transaction.sql ├── IsNumeric_BUG.sql ├── JobDuration.sql ├── Job_duration.sql ├── Kill All the SPIDS to Single DB.sql ├── Kill Blocking SPID.sql ├── ListAvailableDMOs_Ch05_PowerOfDynamicManagementViews&Functions.sql ├── Local Time and UTC Time.sql ├── MANUAL-SqlDependencySetup.sql ├── Max Memory Setting for 2 clusters running.sql ├── Michelle Ufford Index Maintenance v41 _ObjectNamesChanged.sql ├── Michelle Ufford Index Maintenance v41.sql ├── Migrate SQL Agent Jobs.sql ├── Monitor Identity Field Values Used.sql ├── MonitorBlockingScript_Ch08_BlockingAndLocking.sql ├── OpenSQLServerPort.bat ├── Operator_DBA.sql ├── OptimalMaxServerMemory_New_Multi-Version.sql ├── PBMViewEnabledPoliciesScript_Ch10_PolicyBasedManagement.sql ├── PITWaitTypeScript_Ch07_RollingYourOwn.sql ├── PKtoFK.sql ├── P_SMART_REINDEX.sql ├── P_UPDATESTATISTICS.sql ├── PageSplitTrackingRelatedQueries_Ch04_PageSplitTracking.sql ├── Parse Comma Delimited Values to Table.sql ├── Partition Overview Overloaded Partitions.sql ├── Partition Overview.sql ├── Partition to FileGroup mapping.sql ├── Partitioning Key.sql ├── QuerySystemHeathSessionForErrors_Ch08_MonitoringErrorsWithExtendedEvents.sql ├── QuickIdxFrag_Chap04_IndexFragmentation.sql ├── RESULTS.TXT ├── ReIndexScript.sql ├── ReSeed_BusinessDB.sql ├── Rebuild All Indexes On Single Table SQL2005.sql ├── Rebuild All Indexes On Single Table.sql ├── Rebuild Indexes Using Cursor.sql ├── RebuildReorganizeIndexesForAllDbsSQL2005.sql ├── RebuildReorganizeIndexesForSingleDbSQL2005.sql ├── RedGate_SQL_Monitor_Index_Frag_Script.sql ├── Redeploy ServiceContractMove CLR Store Proc TO CP.sql ├── Remove Spaces and Colons From Date.sql ├── RemoveTDE.sql ├── Rename Database.sql ├── Rename SA account.sql ├── ReplicationLogReaderMonitorCode.sql ├── ReplicationLogReaderMonitorCode_SAMPLE.sql ├── Restore Database From Database Snapshot.sql ├── RestoreTDE.sql ├── RetrieveIndexStats.sql ├── RetrieveIndexStats_CreateTableIndexStatProc.sql ├── Review Locks.sql ├── Revoke Connect Permission to Guest User.sql ├── SANTEST.BAT ├── SANTEST.txt ├── SP Start Job With Wait.sql ├── SQL 2005 ALERTS.sql ├── SQL DBA CheckDB Process.doc ├── SQL DBA Deployment Script.doc ├── SQL Server 2005 Diagnostic Information Queries.sql ├── SQL Server 2008 Diagnostic Information Queries.sql ├── SQL Server Agent Job Troubleshooting.sql ├── SQL Server Alerts From Healthy SQL.sql ├── SQL Top 20.sql ├── SQLIO Proc Execution.sql ├── SQLIO Proc and Tables.sql ├── SQLIOTest.txt ├── SQLIO_TestPass Queried.sql ├── SSB_AZURE_SQL_CLIENT_DW.sql ├── SSB_TransLogMonitor Job.sql ├── SSIS 32_64 bit Reg Unreg DLL.txt ├── STRING_SPLIT Sample.sql ├── Scan DB code for Problems.sql ├── Script Table Keys.sql ├── Send Email With CSV File Attached.sql ├── Send Email for Service Restarts.sql ├── ServiceContractsMovement.dll ├── Set Default Database for Logins without Default Database.sql ├── SetupTDE.sql ├── Shrink TLOG File and Grow it to Lower the VLF Number for Single Database.sql ├── Space Used Analyzer Procedure.sql ├── Split Comma Seperated String Using XML.sql ├── Stats Update Date.sql ├── StatusOfTDE.sql ├── Step 1 Store Create FK Information.sql ├── Step 2 Store Drop FK Information.sql ├── Step 3 Drop Foreign Keys.sql ├── Step 4 Create Foreign Keys.sql ├── Step 5 Drop Create FK and Drop FK Tables.sql ├── Store DBCC CheckDB With TableResults.sql ├── Suspect Pages Alert Monitor.sql ├── Suspect Pages Alert.sql ├── Sync Database Users To Logins.sql ├── System.Core.dll ├── TSA BCP TEST.sql ├── Testresult1.txt ├── Top Waits.sql ├── Top of The Hour.sql ├── TransLogMonitor Job.sql ├── TransLogMonitor Table.sql ├── Transfer Logins.sql ├── Trap xp_cmdshell Error Message and Raiserror.sql ├── Try Catch Block with Commit RollBack Trx and Raise Error Short.sql ├── Try Catch Block with Commit RollBack Trx and Raise Error.sql ├── Try Catch Block with Commit RollBack Trx and Throw Error Short.sql ├── Try Catch Block with Commit RollBack Trx.sql ├── TurnOffTDE.sql ├── TurnOnTDE.sql ├── USP_Import_SQLIO_TestPass.sql ├── Update Job Owner To SA.sql ├── Update Job Steps.sql ├── Update Stats For Tables With 1000 Colum Or More.sql ├── Update Using Two Table Join.sql ├── UpgradeTemplate.xaml ├── Wait Stats Troubleshooting.sql ├── When Backup Restore Index Will Finish.sql ├── WhoIsActive_Query.sql ├── XML Dynamic Reading.sql ├── XML Query Exist Method Sample.sql ├── XML Sample.sql ├── _1_TransactionLog_Table_Create.sql ├── _2_sp_TransLogMonitor_Procedure_Create.sql ├── _3_sp_TransLogMonitorReport_Procedure_Create.sql ├── _4_ADMIN_TransLogMonitor_Job_Create.sql ├── _Admin_PLE_Collection_BackEndTable_Creation.sql ├── _Admin_PLE_Collection_Job_Creation.sql ├── _Admin_WhoIsActive_Collection_BackEndTable_Creation.sql ├── _Admin_WhoIsActive_Collection_Job_Creation.sql ├── _HowToDeplooy_SQLscripts_UsingPowershell.txt ├── _Verizon Metric Collection.sql ├── copy-ISNdbbackuptoContentShare.ps1 ├── dba_Index_defrag stored procedure.sql ├── dba_SpaceUsed.sql ├── dba_indexDefrag_sp.sql ├── dbo.sp_whoisactive_populate.sql ├── del-oldbackups-SystemDbs.ps1 ├── del-oldbackups-UserDBBackupFiles.ps1 ├── del-oldbackups-UserDBTlogs.ps1 ├── deleteold.ps1 ├── get-all-sql-databases.txt ├── get-all-sql-databases_in_subscription.txt ├── param.txt ├── pr_DBAdmin_Loader.sql ├── pr_DatabaseBackup_with_Stripes.sql ├── pr_ExecSQLCmd_Update_for_use_with_Stripes.sql ├── rebuild_indexes_by_db.sql ├── setspn command to be executed.sql ├── spDBA_job_notification.sql ├── sp_Cleanup_Files.sql ├── sp_DBPermissions.sql ├── sp_DatabaseBackupUtility.sql ├── sp_DatabaseRestoreReport.sql ├── sp_DatabaseRestoreUtility.sql ├── sp_DatabaseRestoreUtility_FileInfo.sql ├── sp_EmailWhoIsActive.sql ├── sp_MSforeachdb_sample.sql ├── sp_SQLskills_CheckPlanCache.sql ├── sp_ShinkDatabaseInIncrements.sql ├── sp_SrvPermissions.sql ├── sp_Sync_Files.sql ├── sp_TransLogMonitor.sql ├── sp_TransLogMonitorReport.sql ├── sp_WhoIsActive.sql ├── sp_WhoIsActive_WithBlocking.sql ├── sp_configure settings.sql ├── sp_indexinfo.sql ├── sp_killusers_db.sql ├── sp_sizing.sql ├── sp_sizing_1.sql ├── sp_update_job_for_non_admins.sql ├── sp_update_job_for_non_admins_execution.sql ├── sp_whoisactive_column_list_return.sql ├── spndump.txt ├── sqlio.exe ├── sys2.buffer_cache_usage.sql ├── sys2.database_backup_info (1).sql ├── sys2.database_backup_info.sql ├── sys2.databases_files (1).sql ├── sys2.databases_files.sql ├── sys2.indexes (1).sql ├── sys2.indexes.sql ├── sys2.indexes_operational_stats (1).sql ├── sys2.indexes_operational_stats.sql ├── sys2.indexes_per_table (1).sql ├── sys2.indexes_per_table.sql ├── sys2.indexes_physical_stats (1).sql ├── sys2.indexes_physical_stats.sql ├── sys2.indexes_size (1).sql ├── sys2.indexes_size.sql ├── sys2.indexes_usage_stats (1).sql ├── sys2.indexes_usage_stats.sql ├── sys2.logs_usage.sql ├── sys2.missing_indexes (1).sql ├── sys2.missing_indexes.sql ├── sys2.objects_data_spaces (1).sql ├── sys2.objects_data_spaces.sql ├── sys2.objects_dependencies (1).sql ├── sys2.objects_dependencies.sql ├── sys2.objects_partition_ranges (1).sql ├── sys2.objects_partition_ranges.sql ├── sys2.plan_cache_size (1).sql ├── sys2.plan_cache_size.sql ├── sys2.query_memory_grants (1).sql ├── sys2.query_memory_grants.sql ├── sys2.query_stats.sql ├── sys2.stats (1).sql ├── sys2.stats.sql ├── sys2.stp_get_databases_space_used_info.sql ├── sys2.tables_columns.sql ├── tr_SysJobs_enabled.sql ├── usp_LogWatch.sql ├── usp_helpindexusagestats.sql ├── usp_tables_compress_report.sql └── who_is_active_v11_32.sql /##040.Set model FileGrowth 256MB.sql: -------------------------------------------------------------------------------- 1 | USE [master] 2 | GO 3 | ALTER DATABASE [model] MODIFY FILE ( NAME = N'modeldev', FILEGROWTH = 256MB) 4 | GO 5 | -------------------------------------------------------------------------------- /020.Alert.Add trans log backup as response.sql: -------------------------------------------------------------------------------- 1 | /* 2 | 8/29/2001 - SRB 3 | Add a response to the tran log full alert to run the tran log backup job automatically. 4 | **NOTE. This does not factor in litespeed enabled jobs...yet. 5 | */ 6 | 7 | 8 | Declare @jobid uniqueidentifier 9 | set @jobid = N'00000000-0000-0000-0000-000000000000' 10 | 11 | use msdb; 12 | SELECT @jobid = [job_id] 13 | FROM [msdb].[dbo].[sysjobs] 14 | where [name] = 'DBAdmin: User DB - STD Transaction Log Backups' 15 | 16 | EXEC msdb.dbo.sp_update_alert @name=N'DBAdmin: Transaction Log Full', 17 | @message_id=9002, 18 | @severity=0, 19 | @enabled=1, 20 | @delay_between_responses=300, 21 | @include_event_description_in=2, 22 | @category_name=N'[Uncategorized]', 23 | @job_id=@jobid 24 | GO 25 | -------------------------------------------------------------------------------- /020.tbl CHECKDB_Schedule.sql: -------------------------------------------------------------------------------- 1 | USE [DBAdmin] 2 | GO 3 | 4 | IF dbo.fn_SQLVersion() >= 9 5 | BEGIN 6 | IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CHECKDB_Schedule]') AND type in (N'U')) 7 | BEGIN 8 | PRINT 'Dropping table [CHECKDB_Schedule] - SQL 2005' 9 | DROP TABLE [dbo].[CHECKDB_Schedule] 10 | END 11 | END 12 | IF dbo.fn_SQLVersion() < 9 13 | BEGIN 14 | PRINT 'DBAdmin CheckDB processing is not written for SQL 2000. Use the Standard Maintenance Plan processing.' 15 | PRINT '*** Processing of this script is being aborted ***' 16 | RAISERROR ('DBAdmin CheckDB processing is not written for SQL 2000', 20, 1) WITH LOG 17 | END 18 | 19 | GO 20 | 21 | CREATE TABLE [dbo].[CHECKDB_Schedule]( 22 | [ScheduleID] [int] NOT NULL, 23 | [Schedule_Day] [int] NOT NULL, 24 | [DatabaseName] [sysname] NOT NULL, 25 | [TableName] [sysname] NOT NULL ) ON [PRIMARY] 26 | 27 | GO 28 | 29 | IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CHECKDB_Schedule]') AND type in (N'U')) 30 | BEGIN 31 | PRINT 'Table [CHECKDB_Schedule] created - SQL 2005' 32 | END 33 | -------------------------------------------------------------------------------- /040.pr_ExecSQLCmd.sql: -------------------------------------------------------------------------------- 1 | USE [DBAdmin] 2 | GO 3 | 4 | IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[pr_ExecSQLCmd]') AND type in (N'P', N'PC')) 5 | BEGIN 6 | PRINT 'Dropping procedure [pr_ExecSQLCmd] - SQL 2008' 7 | DROP PROCEDURE [dbo].[pr_ExecSQLCmd] 8 | END 9 | GO 10 | 11 | /****** Object: StoredProcedure [dbo].[pr_ExecSQLCmd] Script Date: 09/23/2012 10:40:57 ******/ 12 | SET ANSI_NULLS ON 13 | GO 14 | SET QUOTED_IDENTIFIER ON 15 | GO 16 | 17 | CREATE PROCEDURE [dbo].[pr_ExecSQLCmd] 18 | @SQLCmd VARCHAR(max), --NVARCHAR(2048), 19 | @Source VARCHAR(64), 20 | @rc INT = NULL OUTPUT 21 | AS 22 | 23 | IF @Source != 'pr_DatabaseBackup' 24 | BEGIN 25 | PRINT 'Invalid Source Routine - Code execution not allowed' 26 | SELECT @rc = -1 27 | RETURN 28 | END 29 | 30 | SELECT @rc = 0 31 | 32 | BEGIN TRY 33 | EXEC (@SQLCmd) 34 | END TRY 35 | BEGIN CATCH 36 | SELECT @rc = ERROR_NUMBER() 37 | END CATCH 38 | 39 | RETURN 40 | GO 41 | 42 | IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[pr_DatabaseBackup]') AND type in (N'P', N'PC')) 43 | BEGIN 44 | PRINT 'Procedure Created [pr_DatabaseBackup] - SQL 2008' 45 | END 46 | GO 47 | -------------------------------------------------------------------------------- /050.Add SysAdmin Users.sql: -------------------------------------------------------------------------------- 1 | USE [master] 2 | GO 3 | CREATE LOGIN [NQCORP\BRI DBA] FROM WINDOWS WITH DEFAULT_DATABASE=[master] 4 | GO 5 | EXEC master..sp_addsrvrolemember @loginame = N'NQCORP\BRI DBA', @rolename = N'sysadmin' 6 | GO 7 | 8 | -------------------------------------------------------------------------------- /060.Enable SQL Agent Mail Profile.sql: -------------------------------------------------------------------------------- 1 | USE [msdb] 2 | GO 3 | EXEC msdb.dbo.sp_set_sqlagent_properties @email_save_in_sent_folder=1 4 | GO 5 | EXEC master.dbo.xp_instance_regwrite N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\SQLServerAgent', N'UseDatabaseMail', N'REG_DWORD', 1 6 | GO 7 | 8 | DECLARE @profile_name SYSNAME; 9 | SET @profile_name = @@SERVERNAME; 10 | EXEC master.dbo.xp_instance_regwrite N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\SQLServerAgent', N'DatabaseMailProfile', N'REG_SZ', @profile_name 11 | GO 12 | -------------------------------------------------------------------------------- /1 Disable Jobs.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/himadanreddy/SQL-DBA-SCRIPTS/3111841fe0efca6d018929c71d2201506912ddcb/1 Disable Jobs.sql -------------------------------------------------------------------------------- /2 Stop Running Jobs and Log the Step executing.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/himadanreddy/SQL-DBA-SCRIPTS/3111841fe0efca6d018929c71d2201506912ddcb/2 Stop Running Jobs and Log the Step executing.sql -------------------------------------------------------------------------------- /3 Create Database DDL Audit Trigger.sql: -------------------------------------------------------------------------------- 1 | USE [DBA] 2 | GO 3 | 4 | SET ANSI_NULLS ON 5 | GO 6 | 7 | SET QUOTED_IDENTIFIER ON 8 | GO 9 | 10 | 11 | CREATE TRIGGER [Database_DDL_Audit] ON DATABASE 12 | FOR DDL_DATABASE_LEVEL_EVENTS 13 | AS 14 | BEGIN 15 | SET NOCOUNT ON; 16 | DECLARE @EventDataXml XML; 17 | DECLARE @SchemaName SYSNAME; 18 | DECLARE @ObjectName SYSNAME; 19 | DECLARE @EventType SYSNAME; 20 | 21 | -- getting back event data 22 | SET @EventDataXml = EVENTDATA(); 23 | 24 | SELECT 25 | @EventType = @EventDataXml.value('(/EVENT_INSTANCE/EventType)[1]', 'SYSNAME') 26 | , @SchemaName = @EventDataXml.value('(/EVENT_INSTANCE/SchemaName)[1]', 'SYSNAME') 27 | , @ObjectName = @EventDataXml.value('(/EVENT_INSTANCE/ObjectName)[1]', 'SYSNAME'); 28 | 29 | INSERT INTO [DBA].dbo.[AuditLog] ( 30 | [CreateDate],[LoginName], [ComputerName],[ProgramName],[DBName],[SQLEvent], [SchemaName], [ObjectName], [SQLCmd], [XmlEvent] 31 | ) 32 | SELECT 33 | GETDATE(), 34 | SUSER_NAME(), 35 | HOST_NAME(), 36 | PROGRAM_NAME(), 37 | ISNULL(@EventDataXml.value('(/EVENT_INSTANCE/DatabaseName)[1]', 'SYSNAME'), DB_NAME()), 38 | @EventType, 39 | @SchemaName, 40 | @ObjectName, 41 | @EventDataXml.value('(/EVENT_INSTANCE/TSQLCommand)[1]', 'NVARCHAR(MAX)'), 42 | @EventDataXml 43 | ; 44 | END; 45 | 46 | 47 | GO 48 | 49 | ENABLE TRIGGER [Database_DDL_Audit] ON DATABASE; 50 | GO 51 | -------------------------------------------------------------------------------- /3 Start Jobs at the step where they were stopped.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/himadanreddy/SQL-DBA-SCRIPTS/3111841fe0efca6d018929c71d2201506912ddcb/3 Start Jobs at the step where they were stopped.sql -------------------------------------------------------------------------------- /4 Enable Jobs Which Were Disabled.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/himadanreddy/SQL-DBA-SCRIPTS/3111841fe0efca6d018929c71d2201506912ddcb/4 Enable Jobs Which Were Disabled.sql -------------------------------------------------------------------------------- /AA Install SQL from Command Line.txt: -------------------------------------------------------------------------------- 1 | setup.exe /ACTION=INSTALL /FEATURES=SQL,Tools /INSTANCENAME=MSSQLSERVER /AGTSVCACCOUNT=”NT AUTHORITY\Network Service” /AGTSVCSTARTUPTYPE=Automatic 2 | /SQLSVCACCOUNT=”NT AUTHORITY\Network Service” /SQLSYSADMINACCOUNTS=”BUILTIN\ADMINISTRATORS” /SQLSVCSTARTUPTYPE=Automatic 3 | /SECURITYMODE=SQL /SAPWD=NQCorp123 /TCPENABLED=1 4 | -------------------------------------------------------------------------------- /AA Install SQL from Command Line2.txt: -------------------------------------------------------------------------------- 1 | --Download and extract the update and use the following command to slipstream latest service pack or cu to installation 2 | D:\setup.exe /Action=Install /UpdateEnabled=TRUE /UpdateResource="C:\temp\sql2017cu4" -------------------------------------------------------------------------------- /ActiveXESessions_SystemHealthInfo_Ch06_ExpandingTheToolset.sql: -------------------------------------------------------------------------------- 1 | --List Active Extended Event (XE) Sessions on your SQL Server 2 | select * from sys.dm_xe_sessions 3 | GO 4 | 5 | -- Information caputre for system_health_session 6 | 7 | select event_name,name from sys.dm_xe_session_events e 8 | inner join sys.dm_xe_sessions s 9 | on e.event_session_address = s.address 10 | where name='system_health' 11 | 12 | GO 13 | 14 | -- Event session name and target information 15 | SELECT 16 | es.name AS session_name, 17 | tg.name AS target_name 18 | FROM sys.server_event_sessions AS es 19 | JOIN sys.server_event_session_targets AS tg 20 | ON es.event_session_id = tg.event_session_id 21 | GO 22 | 23 | -------------------------------------------------------------------------------- /Add Email Notification For Failed SQL Server Agent Jobs.sql: -------------------------------------------------------------------------------- 1 | --Create notifications for failed jobs with one easy script 2 | --Here an easy way to setup alerts for all sql agent jobs. 3 | --Typically I use this to send an email alert when a job fails. 4 | -- I always setup a group email address rather than individuals to make this a one-time setup. 5 | 6 | 7 | USE [msdb] 8 | GO 9 | --create a DBA Team operator 10 | EXEC msdb.dbo.sp_add_operator @name=N'Production DBA Team', -- Change this to the operator you need to be notified. 11 | @enabled=1, 12 | @email_address=N'DBAS@yourdomain.com' -- Change this to the email address of the operator. 13 | GO 14 | --add notifications for failure to all jobs 15 | DECLARE @QuotedIdentifier char(1); SET @QuotedIdentifier = '' -- use '''' for single quote 16 | DECLARE @ListDelimeter char(1); SET @ListDelimeter = ';' 17 | DECLARE @CSVlist varchar(max) --use varchar(8000) for SQL Server 2000 18 | 19 | --no event log, email on failure 20 | SELECT @CSVlist = COALESCE(@CSVlist + @ListDelimeter, '') + @QuotedIdentifier + 21 | ' 22 | EXEC msdb.dbo.sp_update_job @job_id=N''' 23 | + convert(varchar(max),[job_id]) + 24 | ''', 25 | @notify_level_eventlog=0, 26 | @notify_level_email=2, 27 | @notify_email_operator_name=N''DBA Team''' -- Change this to the operator you need to be notified. 28 | + @QuotedIdentifier 29 | from msdb.dbo.sysjobs 30 | 31 | print @csvlist 32 | --EXEC (@CSVlist) 33 | GO -------------------------------------------------------------------------------- /Add Gmail as Database Mail Account.sql: -------------------------------------------------------------------------------- 1 | -- Add gmail account as Profile 2 | 3 | EXEC sys.sp_configure N'show advanced options',1 4 | go 5 | reconfigure 6 | go 7 | 8 | EXEC sys.sp_configure N'Database Mail XPs', N'1' 9 | GO 10 | RECONFIGURE 11 | GO 12 | EXECUTE msdb.dbo.sysmail_add_profile_sp 13 | @profile_name=N'Gmail Notification Account', 14 | @description=N'Email Notifications from SQL Server using Gmail Account' 15 | GO 16 | EXECUTE msdb.dbo.sysmail_add_principalprofile_sp 17 | @principal_name=N'guest', 18 | @profile_name=N'Gmail Notification Account', 19 | @is_default=1 20 | GO 21 | 22 | EXECUTE msdb.dbo.sysmail_add_account_sp 23 | @account_name='Gmail Notifications', 24 | @email_address='bulentgucuk@gmail.com', 25 | @display_name='SQL Server Gmail Notifications', 26 | @replyto_address='bulentgucuk@gmail.com', 27 | @description='Email Address for sending Notifications using Gmail', 28 | @mailserver_name='smtp.gmail.com', 29 | @mailserver_type='SMTP', 30 | @port=587, 31 | @username='bulentgucuk@gmail.com', 32 | @password = 'Kehribar', ----- CHANGE THE PASSWORD!!!!!!!!!!!!! 33 | @use_default_credentials=0, 34 | @enable_ssl=1 35 | 36 | EXECUTE msdb.dbo.sysmail_add_profileaccount_sp 37 | @profile_name=N'Gmail Notification Account', 38 | @account_name=N'Gmail Notifications', 39 | @sequence_number = 1 ; 40 | GO -------------------------------------------------------------------------------- /Add Linked Server.sql: -------------------------------------------------------------------------------- 1 | -- ADD LINKED SERVER PASSING THE LOGIN USED FOR KERBEROS AUTH 2 | USE [master] 3 | GO 4 | IF NOT EXISTS ( 5 | SELECT 1 6 | FROM SYS.servers 7 | WHERE name = 'SQLCLR07-P' 8 | ) 9 | BEGIN 10 | EXEC master.dbo.sp_addlinkedserver @server = N'SQLCLR07-P', @srvproduct=N'SQL Server' 11 | EXEC master.dbo.sp_addlinkedsrvlogin @rmtsrvname = N'SQLCLR07-P', @locallogin = NULL , @useself = N'True' 12 | END 13 | GO 14 | 15 | -------------------------------------------------------------------------------- /Add SQL Agent Operate and Assign it to All Jobs for Failure.sql: -------------------------------------------------------------------------------- 1 | USE MSDB 2 | select sj.name, sj.enabled, sj.category_id, sj.job_id 3 | FROM dbo.sysjobs sj 4 | where sj.category_id = 3 5 | order by sj.name 6 | 7 | USE [msdb] 8 | GO 9 | 10 | -- Create Operator [SQL Agent Monitoring] 11 | IF NOT EXISTS (SELECT name FROM msdb.dbo.sysoperators WHERE name = N'SQL Agent Monitoring') 12 | EXEC msdb.dbo.sp_add_operator @name=N'SQL Agent Monitoring', 13 | @enabled=1, 14 | @weekday_pager_start_time=90000, 15 | @weekday_pager_end_time=180000, 16 | @saturday_pager_start_time=90000, 17 | @saturday_pager_end_time=180000, 18 | @sunday_pager_start_time=90000, 19 | @sunday_pager_end_time=180000, 20 | @pager_days=0, 21 | @email_address=N'monitoring-sqlagent@ssbinfo.com', 22 | @category_name=N'[Uncategorized]' 23 | GO 24 | 25 | DECLARE 26 | @Operator varchar(50) 27 | , @AlertText varchar(max); 28 | 29 | SET @Operator = 'SQL Agent Monitoring'; 30 | SET @AlertText = ''; 31 | 32 | --Create the alert text 33 | SELECT @AlertText = 'EXEC msdb.dbo.sp_update_job 34 | @job_ID = ''' + convert(varchar(50),job_id) + ''' , 35 | @notify_level_email = 2, 36 | @notify_email_operator_name = ''' + @operator + '''; ' 37 | + char(10) + @AlertText 38 | FROM dbo.sysjobs sj 39 | WHERE sj.category_id <> 3 -- category_id = 3 is 'Database Maintenance' category 40 | 41 | --Print the alert text and confirm it is valid before exec 42 | PRINT @AlertText; 43 | 44 | --Uncomment below and comment the PRINT to exec alerts 45 | EXEC (@AlertText); 46 | 47 | GO 48 | -------------------------------------------------------------------------------- /AllDeadLockScripts_Ch08_Deadlocks.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/himadanreddy/SQL-DBA-SCRIPTS/3111841fe0efca6d018929c71d2201506912ddcb/AllDeadLockScripts_Ch08_Deadlocks.sql -------------------------------------------------------------------------------- /Alter Database Logical File Names.sql: -------------------------------------------------------------------------------- 1 | 2 | --ALTER DATABASE database_name MODIFY FILE ( NAME = logical_file_name, NEWNAME = new_logical_name ) 3 | 4 | ALTER DATABASE SOCPlatform_BETA MODIFY FILE ( NAME = 'LYCEUM', NEWNAME = 'SOCPlatform_Primary') 5 | GO 6 | ALTER DATABASE SOCPlatform_BETA MODIFY FILE ( NAME = 'LYCEUM_LOG', NEWNAME = 'SOCPlatform_Log') 7 | -------------------------------------------------------------------------------- /Attach DB File Without Log File.sql: -------------------------------------------------------------------------------- 1 | USE master; 2 | GO 3 | -- Detach the db 4 | exec sp_detach_db ODSQA; 5 | 6 | -- Delete the log file 7 | EXEC master.dbo.xp_cmdshell 'del D:\ODS_QA.LDF', NO_OUTPUT; 8 | 9 | -- Attach the database with new log 10 | CREATE DATABASE ODSQA 11 | ON (NAME = 'ODS_QA', 12 | FILENAME = 'H:\ODS_QA.MDF') 13 | FOR ATTACH_REBUILD_LOG; 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /Attach database using Create Database.sql: -------------------------------------------------------------------------------- 1 | USE MASTER 2 | GO 3 | CREATE DATABASE DatabaseNameToBeAttached 4 | ON (FILENAME = 'C:\Data\Databases\DatabaseNameToBeAttached_Data.mdf'), 5 | (FILENAME = 'C:\Data\Databases\DatabaseNameToBeAttached_Log.ldf') 6 | FOR ATTACH; 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /Azure Handy T-SQL.sql: -------------------------------------------------------------------------------- 1 | --Creating a database 2 | 3 | CREATE DATABASE [MeeTwoDB] 4 | (MAXSIZE = 5GB, EDITION = 'standard', SERVICE_OBJECTIVE = 'S2') ; 5 | 6 | 7 | --Checking details 8 | 9 | SELECT Edition = DATABASEPROPERTYEX('MeeTwoDB', 'Edition'), 10 | ServiceObjective = DATABASEPROPERTYEX('MeeTwoDB', 'ServiceObjective'); 11 | 12 | 13 | --Upgrading a database 14 | 15 | ALTER DATABASE [MeeTwoDB] MODIFY (EDITION = 'Premium', SERVICE_OBJECTIVE = 'P1'); 16 | 17 | 18 | -- Recheck 19 | SELECT Edition = DATABASEPROPERTYEX('MeeTwoDB', 'Edition'), 20 | ServiceObjective = DATABASEPROPERTYEX('MeeTwoDB', 'ServiceObjective'); 21 | 22 | --Database names and service tiers 23 | --Execute in the master database 24 | 25 | SELECT d.name, 26 | s.database_id, 27 | s.edition, 28 | s.service_objective, 29 | (CASE WHEN s.elastic_pool_name IS NULL 30 | THEN 'No Elastic Pool used' 31 | ELSE s.elastic_pool_name 32 | END) AS [Elastic Pool details] 33 | FROM sys.databases d 34 | JOIN sys.database_service_objectives s 35 | ON d.database_id = s.database_id; 36 | 37 | 38 | --Move a database into an Elastic Pool 39 | 40 | ALTER DATABASE MeeTwoDB 41 | MODIFY ( SERVICE_OBJECTIVE = ELASTIC_POOL ( name = SQLPOOL ) ) ; 42 | 43 | --Checking operations 44 | 45 | SELECT * 46 | FROM sys.dm_operation_status 47 | ORDER BY start_time DESC; 48 | 49 | --Renaming a database 50 | 51 | ALTER DATABASE facedb_restored 52 | Modify Name = facedb; 53 | 54 | --Indexing Information 55 | 56 | EXEC sp_BlitzIndex @mode = 4; 57 | 58 | 59 | 60 | -------------------------------------------------------------------------------- /Azure SQL Database Resoruce Metrics.sql: -------------------------------------------------------------------------------- 1 | DECLARE @s datetime; 2 | DECLARE @e datetime; 3 | SET @s= DateAdd(d,-15,GetUTCDate()); 4 | SET @e= GETUTCDATE(); 5 | SELECT start_time 6 | , end_time 7 | , database_name 8 | , sku 9 | , storage_in_megabytes 10 | , avg_cpu_percent 11 | , avg_data_io_percent 12 | , avg_log_write_percent 13 | , max_worker_percent 14 | , dtu_limit 15 | FROM sys.resource_stats 16 | WHERE start_time BETWEEN @s AND @e 17 | 18 | SELECT * FROM 19 | sys.dm_db_resource_stats -------------------------------------------------------------------------------- /AzureSQLdatabase_UpdateFirewallRule.sql: -------------------------------------------------------------------------------- 1 | /**** 2 | -- In the master database l2oqghb8m9.database.windows.net 3 | SELECT * 4 | FROM sys.firewall_rules 5 | WHERE name like '%Ginger%' 6 | ORDER BY start_ip_address, name; 7 | ***/ 8 | 9 | 10 | -- In the master database l2oqghb8m9.database.windows.net 11 | exec sp_set_firewall_rule N'Ginger - home office', '71.206.124.94', '71.206.124.94'; 12 | 13 | -------------------------------------------------------------------------------- /AzureSQLdatabase_UpdateFirewallRule_2.sql: -------------------------------------------------------------------------------- 1 | -- In the Azure SQL Master database. 2 | SELECT * FROM sys.firewall_rules ORDER BY start_ip_address, name; 3 | 4 | /** 5 | EXEC sp_set_firewall_rule 6 | N'Carli.Friss_ucdenver.edu_IP' 7 | , '132.194.175.154' 8 | , '132.194.175.154' 9 | ****/ 10 | 11 | -------------------------------------------------------------------------------- /Azure_Database_Firewall_Script.sql: -------------------------------------------------------------------------------- 1 | -- this is for the Azure SQL Database 2 | -- execute in the specific database you need to allow traffic to 3 | SELECT * FROM sys.database_firewall_rules 4 | 5 | GO 6 | 7 | /**** 8 | EXEC sp_set_database_firewall_rule 9 | @name = N'jrooks_ssbinfo.com_ home office_2018-05-29' 10 | , @start_ip_address = '73.229.224.123' 11 | , @end_ip_address = '73.229.224.123'; 12 | 13 | ****/ 14 | -------------------------------------------------------------------------------- /Azure_Delete_Unattached_Managed_Disks.ps1: -------------------------------------------------------------------------------- 1 | # Set deleteUnattachedDisks=1 if you want to delete unattached Managed Disks 2 | # Set deleteUnattachedDisks=0 if you want to see the Id of the unattached Managed Disks 3 | $deleteUnattachedDisks=0 4 | 5 | $managedDisks = Get-AzureRmDisk 6 | 7 | foreach ($md in $managedDisks) { 8 | 9 | # ManagedBy property stores the Id of the VM to which Managed Disk is attached to 10 | # If ManagedBy property is $null then it means that the Managed Disk is not attached to a VM 11 | if($md.ManagedBy -eq $null){ 12 | 13 | if($deleteUnattachedDisks -eq 1){ 14 | 15 | Write-Host "Deleting unattached Managed Disk with Id: $($md.Id)" 16 | 17 | $md | Remove-AzureRmDisk -Force 18 | 19 | Write-Host "Deleted unattached Managed Disk with Id: $($md.Id) " 20 | 21 | }else{ 22 | 23 | $md.Id 24 | 25 | } 26 | 27 | } 28 | 29 | } -------------------------------------------------------------------------------- /Azure_Firewall_Script.sql: -------------------------------------------------------------------------------- 1 | -- This is for the Azure SQL Server (logical server) 2 | -- Execute the script in the master database 3 | SELECT * 4 | FROM sys.firewall_rules 5 | WHERE NAME LIKE '%gucuk%' 6 | ORDER BY name; 7 | 8 | /*** 9 | DECLARE @name NVARCHAR (128) = 'bgucuk_ssbinfo.com_home_office'; 10 | DECLARE @start_ip_address VARCHAR(50) = '71.33.218.156'; 11 | DECLARE @end_ip_address VARCHAR(50); 12 | 13 | EXEC sp_set_firewall_rule 14 | @name = @name, 15 | @start_ip_address = @start_ip_address, 16 | @end_ip_address = @start_ip_address; 17 | 18 | 19 | EXEC sp_delete_firewall_rule 20 | @name = N''; 21 | 22 | ***/ 23 | -------------------------------------------------------------------------------- /BCP Out Sample.sql: -------------------------------------------------------------------------------- 1 | SET NOCOUNT ON; 2 | GO 3 | SET ANSI_PADDING ON; 4 | GO 5 | SET QUOTED_IDENTIFIER ON; 6 | GO 7 | 8 | DECLARE @DatabaseName VARCHAR(32) = 'CU' 9 | , @ServerName VARCHAR(32) = 'SSBCIDW04' 10 | , @BcpFileLocation VARCHAR(128) = 'D:\'; 11 | 12 | IF OBJECT_ID('tempdb..#BcpOut') IS NOT NULL 13 | DROP TABLE #BcpOut; 14 | 15 | CREATE TABLE #BcpOut ( 16 | RowId INT IDENTITY (1,1) NOT NULL 17 | , DatabaseName VARCHAR(32) NOT NULL 18 | , TableName VARCHAR(128) NOT NULL 19 | , BcpFileLocation VARCHAR(128) NOT NULL 20 | , ServerName VARCHAR(32) NOT NULL 21 | , OpStartDateTime DATETIME NULL 22 | , OpEndDateTime DATETIME NULL 23 | ) 24 | 25 | INSERT INTO #BcpOut 26 | ( 27 | DatabaseName , 28 | TableName , 29 | BcpFileLocation , 30 | ServerName 31 | ) 32 | VALUES 33 | (@DatabaseName, 'dbo.TK_TRANS_ITEM_EVENT', @BcpFileLocation, @ServerName); 34 | 35 | DECLARE @cmd VARCHAR(MAX) 36 | , @MaxRowId INT 37 | 38 | SELECT @MaxRowId = MAX(RowId) 39 | FROM #BcpOut 40 | 41 | WHILE @MaxRowId > 0 42 | BEGIN 43 | 44 | SELECT @cmd = 'EXEC XP_CMDSHELL ''BCP ' + DatabaseName + '.' + TableName + ' OUT ' + BcpFileLocation + TableName + '.dat -n -b 5000 -E -T -S ' + ServerName + '''' 45 | FROM #BcpOut 46 | WHERE RowId = @MaxRowId; 47 | 48 | UPDATE #BcpOut 49 | SET OpStartDateTime = GETDATE() 50 | WHERE RowId = @MaxRowId; 51 | 52 | PRINT @cmd 53 | --EXEC (@cmd) 54 | 55 | UPDATE #BcpOut 56 | SET OpEndDateTime = GETDATE() 57 | WHERE RowId = @MaxRowId; 58 | 59 | SELECT @MaxRowId = @MaxRowId - 1; 60 | END 61 | -------------------------------------------------------------------------------- /Backup File CleanUp.sql: -------------------------------------------------------------------------------- 1 | DECLARE @physical_name varchar(260), 2 | @cmd nvarchar(500) 3 | Declare TNAMES_CURSOR CURSOR FOR 4 | SELECT DISTINCT(b.physical_device_name) 5 | FROM backupset a, backupmediafamily b 6 | WHERE a.type= 'D' AND a.backup_start_date >= getdate() - 3 AND 7 | a.backup_start_date <= getdate() - 1 AND 8 | a.media_set_id = b.media_set_id AND 9 | b.physical_device_name LIKE '%Backup%' 10 | --and b.physical_device_name NOT LIKE '%example%' 11 | 12 | OPEN TNAMES_CURSOR 13 | 14 | FETCH NEXT FROM TNAMES_CURSOR 15 | INTO @physical_name 16 | 17 | WHILE (@@fetch_status <> -1) 18 | BEGIN 19 | IF (@@fetch_status <>-2) 20 | BEGIN 21 | SELECT @cmd = 'del /A: -A ' + @physical_name 22 | PRINT @CMD 23 | --EXEC master.dbo.xp_cmdshell @cmd 24 | END 25 | 26 | FETCH NEXT FROM tnames_cursor INTO @physical_name 27 | 28 | END 29 | 30 | DEALLOCATE tnames_cursor 31 | 32 | 33 | -------------------------------------------------------------------------------- /Backup Tlog files Using Powershell.txt: -------------------------------------------------------------------------------- 1 | #load SQL snap-in 2 | Add-PSSnapin *SQL* 3 | 4 | #pull the current date 5 | $date = Get-Date -Format yyyyddMM_hhmmss 6 | 7 | #set location for the backup files 8 | $directory = "C:\temp\" 9 | 10 | #Grab the database names, excluding those in Simple Recovery Model 11 | $dbname = dir 'SQLSERVER:\SQL\KRINGER\DEFAULT\Databases' | where {$_.RecoveryModel -notmatch "Simple"} | Select Name 12 | 13 | #Backup each log of user database found, not in SIMPLE recovery. 14 | $dbname | foreach { $_.Name.ToString() } | foreach { $bakfile = "$directory" + $_ + "_" + $date + ".trn"; "Backing up LOG of Database: $_"; Invoke-Sqlcmd -SuppressProviderContextWarning -Query "BACKUP LOG $_ TO DISK=N'$bakfile' WITH INIT";} -------------------------------------------------------------------------------- /Backup database.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/himadanreddy/SQL-DBA-SCRIPTS/3111841fe0efca6d018929c71d2201506912ddcb/Backup database.sql -------------------------------------------------------------------------------- /Blocking.sql: -------------------------------------------------------------------------------- 1 | 2 | 3 | SELECT 4 | t1.resource_type, 5 | t1.resource_database_id, 6 | t1.resource_associated_entity_id, 7 | t1.request_mode, 8 | t1.request_session_id, 9 | t2.blocking_session_id 10 | FROM sys.dm_tran_locks as t1 11 | INNER JOIN sys.dm_os_waiting_tasks as t2 12 | ON t1.lock_owner_address = t2.resource_address; 13 | -------------------------------------------------------------------------------- /Bruins_ClientDW_WhoIsActive.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | Author name: Bulent Gucuk 3 | Created date: 3/1/2019 4 | Purpose: This will kick of the execution of sp_whoisactive in the runbook that webhook created for 5 | 6 | Example: C:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe -NoProfile -WindowStyle Hidden -Command C:\PowerShell\ClientDW_WhoisActive\ClientDW_WhoIsActive.ps1 7 | -Webhook = "https://s13events.azure-automation.net/webhooks?token=iDJ4n1rhqxstECwNaZ9QOY%2fSiI%2fAYEVrVZGcrGlrWXI%3d" 8 | -Method = "Post" 9 | 10 | Copyright © 2019, SSB, All Rights Reserved 11 | #> 12 | 13 | Param 14 | ( 15 | [string] $Webhook, 16 | [string] $Method 17 | ) 18 | 19 | #For testing: Below webhook is for Boston Bruins runbook DBA_srv-bostonbruins-01_db-bostonbruins-prod_whoisactive 20 | #$Webhook = "https://s13events.azure-automation.net/webhooks?token=iDJ4n1rhqxstECwNaZ9QOY%2fSiI%2fAYEVrVZGcrGlrWXI%3d" 21 | #$Method = "Post" 22 | 23 | $Result = Invoke-WebRequest -Uri $Webhook -Method $Method -UseBasicParsing 24 | $Result -------------------------------------------------------------------------------- /Build Comma Seperated Column and Query.sql: -------------------------------------------------------------------------------- 1 | 2 | DECLARE @listStr VARCHAR(255) 3 | SELECT @listStr = COALESCE(@listStr+', ' ,'') + CAST(NAME AS VARCHAR(32)) 4 | FROM SYS.databases 5 | WHERE database_id > 4 6 | ORDER BY name 7 | SELECT @listStr 8 | 9 | DECLARE @Str NVARCHAR (512) 10 | SELECT @Str = 'SELECT * FROM dbo.Products WHERE ProductId in (' + @listStr + ')' 11 | 12 | SELECT @Str 13 | 14 | EXECUTE sp_executesql 15 | @Stmt = @Str 16 | -------------------------------------------------------------------------------- /CPU counts.sql: -------------------------------------------------------------------------------- 1 | -- Physical CPU count 2 | SELECT cpu_count / hyperthread_ratio AS PhysicalCPUsFROM 3 | FROM sys.dm_os_sys_info 4 | 5 | -- Logical CPU count 6 | SELECT cpu_count AS logicalCPUsFROM 7 | FROM sys.dm_os_sys_info -------------------------------------------------------------------------------- /Cached Exec Plan Query.sql: -------------------------------------------------------------------------------- 1 | 2 | 3 | SELECT qplan.Query_Plan, 4 | Stext.text, 5 | qstats.*, 6 | plns.* 7 | FROM SYS.DM_EXEC_CACHED_PLANS AS plns 8 | INNER JOIN SYS.DM_EXEC_QUERY_STATS AS qstats 9 | ON plns.Plan_Handle = qstats.plan_handle 10 | CROSS APPLY SYS.DM_EXEC_QUERY_PLAN(qstats.Plan_Handle) AS qplan 11 | CROSS APPLY SYS.DM_EXEC_SQL_TEXT(QSTATS.Plan_Handle) AS stext 12 | WHERE Qplan.Query_Plan IS NOT NULL 13 | 14 | 15 | -------------------------------------------------------------------------------- /CalculateAllSQLServerPerformanceCounterValues_Ch05_sys.dm_os_performance_countersHowtoReadCalculate .sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | perf1.[object_name], 3 | perf1.counter_name, 4 | perf1.instance_name, 5 | perf1.cntr_type, 6 | 'value' = CASE perf1.cntr_type 7 | WHEN 537003008 -- This counter is expressed as a ratio and requires calculation. (Sql 2000) 8 | THEN CONVERT(FLOAT, 9 | perf1.cntr_value) / 10 | (SELECT CASE perf2.cntr_value 11 | WHEN 0 THEN 1 12 | ELSE perf2.cntr_value 13 | END 14 | FROM sys.dm_os_performance_counters perf2 15 | WHERE (perf1.counter_name + ' ' 16 | = SUBSTRING(perf2.counter_name, 17 | 1, 18 | PATINDEX('% Base%', perf2.counter_name))) 19 | AND perf1.[object_name] = perf2.[object_name] 20 | AND perf1.instance_name = perf2.instance_name 21 | AND perf2.cntr_type in (1073939459,1073939712) 22 | ) 23 | WHEN 537003264 -- This counter is expressed as a ratio and requires calculation. >=SQL2005 24 | THEN CONVERT(FLOAT, 25 | perf1.cntr_value) / 26 | (SELECT CASE perf2.cntr_value 27 | WHEN 0 THEN 1 28 | ELSE perf2.cntr_value 29 | END 30 | FROM sys.dm_os_performance_counters perf2 31 | WHERE (perf1.counter_name + ' ' 32 | = SUBSTRING(perf2.counter_name, 33 | 1, 34 | PATINDEX('% Base%', perf2.counter_name))) 35 | AND perf1.[object_name] = perf2.[object_name] 36 | AND perf1.instance_name = perf2.instance_name 37 | AND perf2.cntr_type in (1073939712) 38 | ) 39 | ELSE perf1.cntr_value -- The values of the other counter types are 40 | -- already calculated. 41 | END 42 | FROM sys.dm_os_performance_counters perf1 43 | WHERE perf1.cntr_type not in (1073939712) -- Don't display the divisors. 44 | ORDER BY 1,2,3,4 45 | -------------------------------------------------------------------------------- /CalculateCumulativeWaitTimesByWaitType_Chap03_SlowPerformance.sql: -------------------------------------------------------------------------------- 1 | Select wait_type, waiting_tasks_count, wait_time_ms as total_wait_time_ms, 2 | 3 | signal_wait_time_ms, 4 | 5 | (wait_time_ms-signal_wait_time_ms) as resource_wait_time_ms 6 | 7 | FROM sys.dm_os_wait_stats 8 | 9 | ORDER BY total_wait_time_ms DESC -------------------------------------------------------------------------------- /CaptureCfgChangesUsingDefaultTrace_Ch10_DefaultTrace.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/himadanreddy/SQL-DBA-SCRIPTS/3111841fe0efca6d018929c71d2201506912ddcb/CaptureCfgChangesUsingDefaultTrace_Ch10_DefaultTrace.sql -------------------------------------------------------------------------------- /Check Azure SQL DB User Role and Role Permissions.sql: -------------------------------------------------------------------------------- 1 | SELECT pr.* 2 | FROM sys.database_principals AS pr 3 | where pr.type <> 'R' 4 | and pr.name like 'Rmahendrakumar%' 5 | 6 | 7 | --List Database Roles and it's members 8 | SELECT r.name AS role_principal_name 9 | , m.name AS member_principal_name 10 | FROM sys.database_role_members rm 11 | JOIN sys.database_principals r 12 | ON rm.role_principal_id = r.principal_id 13 | JOIN sys.database_principals m 14 | ON rm.member_principal_id = m.principal_id 15 | WHERE 1=1 16 | --AND r.name IN ('loginmanager', 'dbmanager') 17 | AND m.name LIKE 'jkoette%' 18 | ; 19 | 20 | --List permissions on schemas for database roles 21 | SELECT state_desc, permission_name, 'ON', class_desc, 22 | SCHEMA_NAME(major_id) AS SCHEMANAME, 23 | 'TO', USER_NAME(grantee_principal_id) AS UserGroup 24 | FROM sys.database_permissions AS Perm 25 | JOIN sys.database_principals AS Prin 26 | ON Perm.major_id = Prin.principal_id AND class_desc = 'SCHEMA' 27 | WHERE 1=1 28 | --AND major_id = SCHEMA_ID('prodcopystg') 29 | AND USER_NAME(grantee_principal_id) LIKE 'CI_ClientAccess%' 30 | ; 31 | -------------------------------------------------------------------------------- /Check Free Space And Truncate.sql: -------------------------------------------------------------------------------- 1 | 2 | -- Find the available space 3 | SELECT name ,size/128.0 - CAST(FILEPROPERTY(name, 'SpaceUsed') AS int)/128.0 AS AvailableSpaceInMB 4 | FROM sys.database_files; 5 | 6 | Declare @SQL VarChar(8000) 7 | Set @SQL = 'DBCC SHOWFILESTATS WITH TABLERESULTS' 8 | If Object_ID('tempdb.dbo.#UsedSpace') > 0 9 | Drop Table #UsedSpace 10 | Create Table #UsedSpace (FileID SmallInt, FileGroup SmallInt, TotalExtents Int, UsedExtents Int, 11 | Name NVarChar(256), FileName NVarChar(512)) 12 | Insert Into #UsedSpace 13 | Exec(@SQL) 14 | Select Name, (TotalExtents * 64) / 1024 As 'TotalSpace', 15 | (UsedExtents * 64) / 1024 As 'UsedSpace', 16 | ((TotalExtents * 64) / 1024) - ((UsedExtents * 64) / 1024) As 'FreeSpace' 17 | From #UsedSpace 18 | order by Name 19 | Drop Table #UsedSpace 20 | 21 | 22 | DBCC SQLPERF(LOGSPACE) 23 | 24 | 25 | DBCC LOGINFO('ODSQA') 26 | 27 | -------------------------------------------------------------------------------- /CheckPoint Free Proc Cache Clean Buffers.sql: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | A checkpoint writes the current in-memory modified pages (known as dirty pages) 4 | and transaction log information from memory to disk and, also, 5 | records information about the transaction log 6 | */ 7 | checkpoint 8 | go 9 | 10 | /* 11 | Removes all elements from the procedure plan cache, 12 | */ 13 | dbcc freeproccache 14 | go 15 | 16 | /* 17 | Use DBCC DROPCLEANBUFFERS to test queries with a cold buffer cache without shutting down and restarting the server. 18 | To drop clean buffers from the buffer pool, first use CHECKPOINT to produce a cold buffer cache. 19 | This forces all dirty pages for the current database to be written to disk and cleans the buffers. 20 | After you do this, you can issue DBCC DROPCLEANBUFFERS command to remove all buffers from the buffer pool. 21 | */ 22 | dbcc dropcleanbuffers 23 | -------------------------------------------------------------------------------- /Clean up Replication.sql: -------------------------------------------------------------------------------- 1 | -- Clean up Replication 2 | 3 | 4 | -- Disable the publication database. 5 | USE TransactionalQA 6 | EXEC sp_removedbreplication 'TransactionalQA'; 7 | 8 | -- Remove the registration of the local Publisher at the Distributor. 9 | USE master 10 | EXEC sp_dropdistpublisher @publisher; 11 | 12 | -- Delete the distribution database. 13 | EXEC sp_dropdistributiondb @distributionDB; 14 | 15 | -- Remove the local server as a Distributor. 16 | EXEC sp_dropdistributor @no_checks = 1,@ignore_distributor =1; 17 | GO -------------------------------------------------------------------------------- /Comma Seperate Mutiple Rows.sql: -------------------------------------------------------------------------------- 1 | BEGIN TRAN 2 | 3 | DECLARE @t TABLE ( fruit VARCHAR(10) ) 4 | 5 | INSERT INTO @t 6 | ( fruit 7 | ) 8 | SELECT 'apple' 9 | UNION ALL 10 | SELECT 'banana' 11 | UNION ALL 12 | SELECT 'tomato' 13 | 14 | SELECT ',' + fruit 15 | FROM @t 16 | FOR XML PATH 17 | 18 | SELECT ',' + fruit 19 | FROM @t 20 | FOR XML PATH('') 21 | 22 | SELECT STUFF(( SELECT ',' + fruit 23 | FROM @t 24 | FOR 25 | XML PATH('') 26 | ), 1, 1, '') AS fruits 27 | 28 | ROLLBACK 29 | 30 | -------------------------------------------------------------------------------- /CompareResourceWaitsVsSignalWaits_Chap03_SignalWaits.sql: -------------------------------------------------------------------------------- 1 | Select 2 | 3 | ResourceWaitTimeMs=sum(wait_time_ms - signal_wait_time_ms) 4 | 5 | ,'%resource waits'= cast(100.0 * sum(wait_time_ms - signal_wait_time_ms) / sum (wait_time_ms) as numeric(20,2)) 6 | 7 | ,SignalWaitTimeMs=sum(signal_wait_time_ms) 8 | 9 | ,'%signal waits' = cast(100.0 * sum(signal_wait_time_ms) / sum (wait_time_ms) as numeric(20,2)) 10 | 11 | from sys.dm_os_wait_stats -------------------------------------------------------------------------------- /Compress Table.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/himadanreddy/SQL-DBA-SCRIPTS/3111841fe0efca6d018929c71d2201506912ddcb/Compress Table.sql -------------------------------------------------------------------------------- /Convert Int to Time Function.sql: -------------------------------------------------------------------------------- 1 | CREATE FUNCTION dbo.udf_Convert_Int_Time (@time_in INT) 2 | RETURNS VARCHAR(8) 3 | AS 4 | BEGIN 5 | DECLARE @time_out VARCHAR(8) 6 | SELECT @time_out = 7 | CASE LEN(@time_in) 8 | WHEN 6 THEN LEFT(CAST(@time_in AS VARCHAR(6)),2) + ':' + SUBSTRING(CAST(@time_in AS VARCHAR(6)), 3,2) + ':' + RIGHT(CAST(@time_in AS VARCHAR(6)), 2) 9 | WHEN 5 THEN '0' + LEFT(CAST(@time_in AS VARCHAR(6)),1) + ':' + SUBSTRING(CAST(@time_in AS VARCHAR(6)), 2,2) + ':' + RIGHT(CAST(@time_in AS VARCHAR(6)), 2) 10 | WHEN 4 THEN '00' + ':' + LEFT(CAST(@time_in AS VARCHAR(6)),2) + ':' + RIGHT(CAST(@time_in AS VARCHAR(6)), 2) 11 | ELSE '00:00:00' --midnight 12 | END --AS converted_time 13 | RETURN @time_out 14 | END 15 | GO 16 | 17 | 18 | /******** 19 | SELECT SJ.[name], SJH.[run_date], 20 | dbo.udf_convert_int_time(SJH.[run_time]) AS run_time 21 | FROM msdb.dbo.[sysjobhistory] SJH 22 | INNER JOIN [msdb].dbo.[sysjobs] SJ ON SJH.[job_id] = SJ.[job_id] 23 | WHERE SJH.[step_id] = 0 24 | ORDER BY SJ.[name] 25 | GO 26 | 27 | ********/ -------------------------------------------------------------------------------- /Create Dynamic Database SnapShot Daily.sql: -------------------------------------------------------------------------------- 1 | ---------------------------------------------------------- 2 | -- Create Snapshot of a Source database in the same folder 3 | ---------------------------------------------------------- 4 | SET NOCOUNT ON; 5 | DECLARE @SourceDBName SYSNAME, 6 | @SnapShotDBName SYSNAME, 7 | @InitRowId INT, 8 | @MaxRowId INT, 9 | @SqlCmd NVARCHAR(MAX) 10 | 11 | SELECT @SourceDBName = DB_NAME() 12 | SELECT @SnapShotDBName = @SourceDBName + '_SnapShot_' + CONVERT(VARCHAR(10), GETDATE(), 112) 13 | 14 | 15 | SELECT @InitRowId = 1, 16 | @SqlCmd = '' 17 | 18 | DECLARE @T TABLE ( 19 | RowId INT IDENTITY (1,1), 20 | Name VARCHAR(256), 21 | FileName VARCHAR(512) 22 | ) 23 | 24 | INSERT INTO @T (Name, FileName) 25 | SELECT '(name = ' + name + ',' , 26 | 'Filename = ''' + REPLACE(REPLACE(physical_name, '.mdf','.SS'),'.ndf','.SS') + '''),' 27 | FROM sys.database_files 28 | WHERE type = 0 29 | 30 | -- Get the max row to loop 31 | SELECT @MaxRowId = MAX(RowId) 32 | FROM @T 33 | 34 | -- Remove the comma at the last file for command to execute 35 | UPDATE @T 36 | SET FileName = REPLACE([FileName], ',' , '') 37 | WHERE RowId = @MaxRowId 38 | 39 | -- Build SQL Command to be executed 40 | WHILE @InitRowId <= @MaxRowId 41 | BEGIN 42 | SELECT @SqlCmd = @SqlCmd + Name + [FileName] + CHAR(13) 43 | FROM @T 44 | WHERE RowId = @InitRowId; 45 | 46 | SELECT @InitRowId = @InitRowId + 1; 47 | END 48 | 49 | SELECT @SqlCmd = 'CREATE DATABASE ' + @SnapShotDBName + ' ON ' + CHAR(13)+@SqlCmd + 'AS SNAPSHOT OF ' + @SourceDBName + ';' 50 | 51 | PRINT @SqlCmd; 52 | EXEC (@SqlCmd); 53 | -------------------------------------------------------------------------------- /Create Extended Event Session 24HourDataCapture.sql: -------------------------------------------------------------------------------- 1 | CREATE EVENT SESSION [24HourDataCapture] ON SERVER 2 | ADD EVENT sqlserver.sql_statement_completed(SET collect_statement=(1) 3 | ACTION(sqlserver.client_app_name,sqlserver.database_id,sqlserver.database_name,sqlserver.query_hash,sqlserver.query_plan_hash,sqlserver.session_id) 4 | WHERE ([package0].[greater_than_uint64]([sqlserver].[database_id],(6)) AND [package0].[equal_boolean]([sqlserver].[is_system],(0)) AND [sqlserver].[client_app_name]<>N'Microsoft SQL Server')) 5 | ADD TARGET package0.event_file(SET filename=N'24HourDataCapture') 6 | WITH (MAX_MEMORY=4096 KB,EVENT_RETENTION_MODE=ALLOW_SINGLE_EVENT_LOSS,MAX_DISPATCH_LATENCY=30 SECONDS,MAX_EVENT_SIZE=0 KB,MEMORY_PARTITION_MODE=NONE,TRACK_CAUSALITY=ON,STARTUP_STATE=ON) 7 | GO 8 | 9 | 10 | -------------------------------------------------------------------------------- /Create Function to Parse String.sql: -------------------------------------------------------------------------------- 1 | 2 | CREATE FUNCTION [dbo].[fnParseStringTSQL] (@string NVARCHAR(MAX),@separator NCHAR(1)) 3 | RETURNS @parsedString TABLE (string NVARCHAR(MAX)) 4 | AS 5 | BEGIN 6 | DECLARE @position int 7 | SET @position = 1 8 | SET @string = @string + @separator 9 | WHILE charindex(@separator,@string,@position) <> 0 10 | BEGIN 11 | INSERT into @parsedString 12 | SELECT substring(@string, @position, charindex(@separator,@string,@position) - @position) 13 | SET @position = charindex(@separator,@string,@position) + 1 14 | END 15 | RETURN 16 | END 17 | go 18 | 19 | SELECT * FROM dbo.fnParseStringTSQL('SQL Server 2000|SQL Server 2005|SQL Server 2008|SQL Server 7.0','|') 20 | GO 21 | SELECT * FROM dbo.fnParseStringTSQL('Apple,Banana,Pear',',') 22 | 23 | -------------------------------------------------------------------------------- /Create Linked Server to Azure Database.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Create new linked server 3 | */ 4 | 5 | -- Make a link to the cloud 6 | EXEC sp_addlinkedserver 7 | @server=N'AzureNFLDB', 8 | @srvproduct=N'Azure SQL Db', 9 | @provider=N'SQLNCLI', 10 | @datasrc=N'xxxxxx.database.windows.net', -- azure db address 11 | @catalog='xxxxxx'; -- azure db name 12 | GO 13 | 14 | --Set up login mapping 15 | EXEC sp_addlinkedsrvlogin 16 | @rmtsrvname = 'AzureNFLDB', 17 | @useself = 'FALSE', 18 | @locallogin=NULL, 19 | @rmtuser = 'xxxxxx', -- remote login 20 | @rmtpassword = 'xxxxxxqqqqwwwwww' -- password 21 | GO 22 | 23 | -- Test the connection 24 | exec sp_testlinkedserver AzureNFLDB; 25 | GO 26 | 27 | -- Sample remote queries to linked server 28 | /*** 29 | --https://msdn.microsoft.com/en-us/library/ms188427.aspx 30 | 31 | SELECT * FROM OPENQUERY (AzureNFLDB , 'select objectname, indexname, commandtype, starttime, endtime from dbo.CommandLog 32 | where starttime > ''20160405'''); 33 | 34 | 35 | SELECT * FROM OPENQUERY (AzureNFLDB , 'declare @d date = getdate() select objectname, indexname, commandtype, starttime, endtime from dbo.CommandLog 36 | where starttime > @d'); 37 | 38 | 39 | DECLARE @Sname SYSNAME = 'AzureNFLDB'; 40 | IF EXISTS (SELECT * 41 | FROM sys.servers 42 | WHERE name = @Sname 43 | ) 44 | BEGIN 45 | DELETE OPENQUERY (AzureNFLDB , 'SELECT ID FROM dbo.CommandLog WHERE starttime < DATEADD(DAY,-30,GETDATE());'); 46 | END 47 | 48 | 49 | DELETE OPENQUERY (AzureNFLDB , 'DECLARE @d DATETIME = DATEADD(DAY, -30, GETDATE()) SELECT ID FROM dbo.CommandLog WHERE starttime < @d'); 50 | 51 | ***/ -------------------------------------------------------------------------------- /Create New DBA Operator.sql: -------------------------------------------------------------------------------- 1 | USE [msdb] 2 | GO 3 | 4 | /****** Object: Operator [BizOpDBA] Script Date: 10/15/2012 08:45:25 ******/ 5 | EXEC msdb.dbo.sp_add_operator @name=N'BizOpDBA', 6 | @enabled=1, 7 | @weekday_pager_start_time=90000, 8 | @weekday_pager_end_time=180000, 9 | @saturday_pager_start_time=90000, 10 | @saturday_pager_end_time=180000, 11 | @sunday_pager_start_time=90000, 12 | @sunday_pager_end_time=180000, 13 | @pager_days=0, 14 | @email_address=N'bgucuk@servicesource.com', 15 | @category_name=N'[Uncategorized]' 16 | GO 17 | 18 | 19 | -------------------------------------------------------------------------------- /Create ProcExec Role and Grant Execution Select on Objects.sql: -------------------------------------------------------------------------------- 1 | -- CREATE ROLE AND ADD ROLE MEMBERS THEN GRANT EXECUTE PERMISSIONS 2 | IF NOT EXISTS ( 3 | SELECT 1 4 | FROM sys.database_principals 5 | WHERE Type = 'R' 6 | AND name = 'ProcExec' 7 | ) 8 | BEGIN 9 | CREATE ROLE ProcExec AUTHORIZATION dbo; 10 | END 11 | 12 | GO 13 | EXEC sp_addrolemember N'ProcExec', N'Peak8DDC\RPhelps' 14 | GO 15 | EXEC sp_addrolemember N'ProcExec', N'Peak8DDC\SQLReportViewer' 16 | GO 17 | 18 | 19 | -- GRANT EXECUTE ON STORED PROCEDURES 20 | SELECT 'GRANT EXECUTE ON ' + QUOTENAME(s1.name) + '.' + QUOTENAME(s.name) + ' TO [ProcExec]' AS GrantExecuteForSPs 21 | FROM sys.procedures AS s 22 | INNER JOIN sys.schemas AS s1 23 | ON s.schema_id = s1.schema_id 24 | AND is_ms_shipped = 0 25 | 26 | UNION ALL 27 | 28 | -- GRANT SELECT FOR TABLE VALUED FUNCTIONS 29 | SELECT 'GRANT SELECT ON ' + QUOTENAME(s.name) + '.' + QUOTENAME(o.name) + ' TO [ProcExec]' AS GrantSelectForTVFs 30 | FROM sys.objects AS O 31 | INNER JOIN sys.schemas AS s 32 | ON o.schema_id = s.schema_id 33 | WHERE type = 'tf' 34 | AND is_ms_shipped = 0 35 | 36 | UNION ALL 37 | 38 | -- GRANT EXECUTE ON SCALAR FUNCTIONS 39 | SELECT 'GRANT EXECUTE ON ' + QUOTENAME(s.name) + '.' + QUOTENAME(o.name) + ' TO [ProcExec]' AS GrantExecuteForScalarFunctions 40 | FROM sys.objects AS O 41 | INNER JOIN sys.schemas AS s 42 | ON o.schema_id = s.schema_id 43 | WHERE type = 'FN' 44 | AND is_ms_shipped = 0 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /Create Random Password.sql: -------------------------------------------------------------------------------- 1 | 2 | 3 | create proc [dbo].uspRandChars 4 | @len int, 5 | @min tinyint = 48, 6 | @range tinyint = 74, 7 | @exclude varchar(50) = '0:;<=>?@O[]`^\/', 8 | @output varchar(50) output 9 | as 10 | declare @char char 11 | set @output = '' 12 | 13 | while @len > 0 begin 14 | select @char = char(round(rand() * @range + @min, 0)) 15 | if charindex(@char, @exclude) = 0 begin 16 | set @output += @char 17 | set @len = @len - 1 18 | end 19 | end 20 | ; 21 | GO 22 | 23 | 24 | declare @newpwd varchar(20) 25 | 26 | 27 | -- all values between ASCII code 48 - 122 excluding defaults 28 | exec [dbo].uspRandChars @len=8, @output=@newpwd out 29 | select @newpwd 30 | 31 | 32 | -- all lower case letters excluding o and l 33 | exec [dbo].uspRandChars @len=10, @min=97, @range=25, @exclude='ol', @output=@newpwd out 34 | select @newpwd 35 | 36 | 37 | -- all upper case letters excluding O 38 | exec [dbo].uspRandChars @len=12, @min=65, @range=25, @exclude='O', @output=@newpwd out 39 | select @newpwd 40 | 41 | 42 | -- all numbers between 0 and 9 43 | exec [dbo].uspRandChars @len=14, @min=48, @range=9, @exclude='', @output=@newpwd out 44 | select @newpwd -------------------------------------------------------------------------------- /Create SQL Login With SID.sql: -------------------------------------------------------------------------------- 1 | -- TRX 2 | CREATE LOGIN IUSR_SQL_TRAN_RW_PROD 3 | WITH PASSWORD = 'PDX5mtcnk8', 4 | SID = 0xF53E371AB4EEAA499E60FB6452A0A259 5 | 6 | -- WEBSITE 7 | CREATE LOGIN IUSR_SQL_WEB_PROD 8 | WITH PASSWORD = 'T5yqz7SP', 9 | SID = 0x81341CD7A514D746A59712F660F31DE2 10 | 11 | 12 | -- WEB READ ONLY LOGIN 13 | CREATE LOGIN IUSR_SQL_WEB_RO_Prod 14 | WITH PASSWORD = 'LdWmp83x5G', 15 | SID = 0x897E6201EA46BC4DA3592064F6858DD2 16 | 17 | 18 | --- UA PROD LOGIN 19 | CREATE LOGIN IUSR_SQL_UA_RW_PROD 20 | WITH PASSWORD = '3FgvwS5trB', 21 | SID = 0x040454DA0B114A46A4C34C7314992282 22 | -------------------------------------------------------------------------------- /Create SSIS Proxy Account.sql: -------------------------------------------------------------------------------- 1 | -- Create a credential containing the domain account PowerDomain\PowerUser and its password 2 | CREATE CREDENTIAL PowerUser WITH IDENTITY = N'Peak8ddc\SQLService', SECRET = N'$$waz00!*' 3 | GO 4 | USE [msdb] 5 | GO 6 | -- Create a new proxy called SSISProxy and assign the PowerUser credentail to it 7 | EXEC msdb.dbo.sp_add_proxy @proxy_name=N'SSISProxy',@credential_name=N'PowerUser',@enabled=1 8 | 9 | -- Grant SSISProxy access to the "SSIS package execution" subsystem 10 | EXEC msdb.dbo.sp_grant_proxy_to_subsystem @proxy_name=N'SSISProxy', @subsystem_id=11 11 | 12 | -- Grant the login testUser the permissions to use SSISProxy 13 | EXEC msdb.dbo.sp_grant_login_to_proxy @login_name = N'PEAK8DDC\rphelps', @proxy_name=N'SSISProxy' 14 | GO -------------------------------------------------------------------------------- /Create Tally Table.sql: -------------------------------------------------------------------------------- 1 | USE tempdb; 2 | GO 3 | ;WITH lv0 AS (SELECT 0 g UNION ALL SELECT 0) 4 | ,lv1 AS (SELECT 0 g FROM lv0 a CROSS JOIN lv0 b) -- 4 5 | ,lv2 AS (SELECT 0 g FROM lv1 a CROSS JOIN lv1 b) -- 16 6 | ,lv3 AS (SELECT 0 g FROM lv2 a CROSS JOIN lv2 b) -- 256 7 | ,lv4 AS (SELECT 0 g FROM lv3 a CROSS JOIN lv3 b) -- 65536 8 | ,Tally (n) AS (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM lv4) 9 | 10 | SELECT * 11 | FROM Tally; 12 | -------------------------------------------------------------------------------- /Create User for Azure SQL Database.sql: -------------------------------------------------------------------------------- 1 | /****** Object: SQL User For Azure SQL Database Create Script Date: 2/9/2018 1:14:55 PM ******/ 2 | DECLARE @UserName SYSNAME = 'ssb_azure_dba' 3 | , @Password NVARCHAR(128) = 'jC73dYDu82BmwYNyTq' 4 | , @RoleName VARCHAR(64) = 'db_owner' 5 | , @str NVARCHAR(1024); 6 | 7 | IF USER_ID(@UserName) IS NULL 8 | BEGIN 9 | SELECT @str = 'CREATE USER ' + QUOTENAME(@UserName) + ' WITH PASSWORD = N' + '''' + @Password + '''' +' , DEFAULT_SCHEMA=[dbo];'; 10 | PRINT @str; 11 | EXEC sp_executesql @stmt = @str; 12 | END 13 | 14 | 15 | SELECT @str = 'ALTER ROLE ' + QUOTENAME(@RoleName) + ' ADD MEMBER ' + QUOTENAME(@UserName) + ';'; 16 | PRINT @str; 17 | EXEC sp_executesql @stmt = @str; 18 | 19 | GO 20 | 21 | /****** Object: SQL User For Azure SQL Database Create Script Date: 2/9/2018 1:14:55 PM ******/ 22 | DECLARE @UserName SYSNAME = 'jmalone@ssbinfo.com' 23 | , @RoleName VARCHAR(64) = 'db_owner' 24 | , @str NVARCHAR(1024); 25 | 26 | IF USER_ID(@UserName) IS NULL 27 | BEGIN 28 | SELECT @str = 'CREATE USER ' + QUOTENAME(@UserName) + ' FROM EXTERNAL PROVIDER;'; 29 | PRINT @str; 30 | EXEC sp_executesql @stmt = @str; 31 | END 32 | 33 | 34 | SELECT @str = 'ALTER ROLE ' + QUOTENAME(@RoleName) + ' ADD MEMBER ' + QUOTENAME(@UserName) + ';'; 35 | PRINT @str; 36 | EXEC sp_executesql @stmt = @str; 37 | 38 | -------------------------------------------------------------------------------- /Create ssb_azure_dba for Azure SQL Database.sql: -------------------------------------------------------------------------------- 1 | /****** Object: SQL User For Azure SQL Database Create Script Date: 2/9/2018 1:14:55 PM ******/ 2 | DECLARE @UserName SYSNAME = 'ssb_azure_dba' 3 | , @Password NVARCHAR(128) = '' 4 | , @RoleName VARCHAR(64) = 'db_owner' 5 | , @str NVARCHAR(1024); 6 | 7 | IF USER_ID(@UserName) IS NULL 8 | BEGIN 9 | SELECT @str = 'CREATE USER ' + QUOTENAME(@UserName) + ' WITH PASSWORD = N' + '''' + @Password + '''' +' , DEFAULT_SCHEMA=[dbo];'; 10 | PRINT @str; 11 | EXEC sp_executesql @stmt = @str; 12 | END 13 | 14 | 15 | SELECT @str = 'ALTER ROLE ' + QUOTENAME(@RoleName) + ' ADD MEMBER ' + QUOTENAME(@UserName) + ';'; 16 | PRINT @str; 17 | EXEC sp_executesql @stmt = @str; 18 | 19 | -------------------------------------------------------------------------------- /CreateCustomDataCollectionScriptForQueryStats_Ch07_DefiningCustomDataCollection.sql: -------------------------------------------------------------------------------- 1 | USE msdb 2 | DECLARE @collection_set_id int 3 | DECLARE @collection_set_uid uniqueidentifier 4 | EXEC sp_syscollector_create_collection_set 5 | @name=N'QueryExecStatsDMV', 6 | @collection_mode=0, 7 | @description=N'HealthySQL sample collection set', 8 | @logging_level=1, 9 | @days_until_expiration=14, 10 | @schedule_name=N'CollectorSchedule_Every_15min', 11 | @collection_set_id=@collection_set_id OUTPUT, 12 | @collection_set_uid=@collection_set_uid OUTPUT 13 | DECLARE @collector_type_uid uniqueidentifier 14 | SELECT @collector_type_uid = collector_type_uid FROM [msdb].[dbo].[syscollector_collector_types] 15 | WHERE name = N'Generic T-SQL Query Collector Type'; 16 | DECLARE @collection_item_id int 17 | EXEC sp_syscollector_create_collection_item 18 | @name=N'Query Stats - Test 1', 19 | @parameters=N' 20 | 21 | 22 | 23 | SELECT * FROM sys.dm_exec_query_stats 24 | 25 | dm_exec_query_stats 26 | 27 | ', 28 | @collection_item_id=@collection_item_id OUTPUT, 29 | @frequency=5, 30 | @collection_set_id=@collection_set_id, 31 | @collector_type_uid=@collector_type_uid 32 | SELECT @collection_set_id as Collection_Set_ID, @collection_set_uid as Collection_Set_UID, 33 | @collection_item_id as Collection_Item_I -------------------------------------------------------------------------------- /CreateHistoricalWaitStatsTable_Ch07_RollingYourOwn.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE [dbo].[waitstats]( 2 | [wait_type] [nvarchar](60) NOT NULL, 3 | [WaitSec] [numeric](26, 6) NULL, 4 | [ResourceSec] [numeric](26, 6) NULL, 5 | [SignalSec] [numeric](26, 6) NULL, 6 | [WaitCount] [bigint] NOT NULL, 7 | [AvgWait_Sec] [numeric](26, 6) NULL, 8 | [AvgRes_Sec] [numeric](26, 6) NULL, 9 | [AvgSig_Sec] [numeric](26, 6) NULL, 10 | [Percentage] [numeric](38, 15) NULL, 11 | [CaptureDate] [datetime] NULL 12 | ) ON [PRIMARY] 13 | GO -------------------------------------------------------------------------------- /CreateMonitoredWaitTypesTable_Ch07_RollingYourOwn.sql: -------------------------------------------------------------------------------- 1 | -- Create Schema 2 | IF SCHEMA_ID('Monitor') IS NULL EXECUTE ('CREATE SCHEMA Monitor'); 3 | -- Create WaitType repository for wait types 4 | IF OBJECT_ID('Monitor.WaitTypes','U') IS NULL 5 | CREATE TABLE Monitor.WaitTypes (wait_type varchar(50),track bit default (1)); 6 | GO 7 | -- Build the repository of available waits from the sys.dm_os_wait_stats DMW 8 | Insert Into Monitor.WaitTypes (wait_type) 9 | Select distinct s.wait_type 10 | From sys.dm_os_wait_stats s; 11 | -- Create clustered and filtered indices 12 | Create Clustered Index CX_waittype on Monitor.WaitTypes(wait_type); 13 | Create Index IX_waittype on Monitor.WaitTypes(wait_type) 14 | Where track = 1; -------------------------------------------------------------------------------- /Create_Pool_Disks.ps1: -------------------------------------------------------------------------------- 1 | $poolName = "Log Pool" #set this 2 | $diskName = "Log Disks" #set this 3 | $FileSystemLabel = "DWLogs" #set this 4 | $Pool = Get-PhysicalDisk -CanPool $True 5 | $PhysicalDisks = Get-PhysicalDisk | Where-Object {$_.CanPool -eq "true"} 6 | New-StoragePool -FriendlyName $poolName -StorageSubsystemFriendlyName "Windows Storage*" -PhysicalDisks $PhysicalDisks | New-VirtualDisk -FriendlyName $diskName -Interleave 262144 -NumberOfColumns $pool.Count -ResiliencySettingName simple –UseMaximumSize |Initialize-Disk -PartitionStyle GPT -PassThru |New-Partition -AssignDriveLetter -UseMaximumSize |Format-Volume -FileSystem NTFS -NewFileSystemLabel $FileSystemLabel -AllocationUnitSize 65536 -Confirm:$false -------------------------------------------------------------------------------- /Create_red-gate_monitor_user.sql: -------------------------------------------------------------------------------- 1 | --in master 2 | CREATE LOGIN [ssb_redgate_monitor] WITH PASSWORD = 'IbMA6DWT$tt*5^z5g7$NQhYy' 3 | 4 | CREATE USER [ssb_redgate_monitor] FROM LOGIN [ssb_redgate_monitor] 5 | WITH --PASSWORD = N'IbMA6DWT$tt*5^z5g7$NQhYy' , 6 | DEFAULT_SCHEMA=[dbo]; 7 | 8 | -- in sql db 9 | CREATE USER [ssb_redgate_monitor] FROM LOGIN [ssb_redgate_monitor] 10 | WITH --PASSWORD = N'IbMA6DWT$tt*5^z5g7$NQhYy' , 11 | DEFAULT_SCHEMA=[dbo]; 12 | 13 | ALTER ROLE db_owner ADD MEMBER [ssb_redgate_monitor] -------------------------------------------------------------------------------- /DBA Check Identity Value Table.sql: -------------------------------------------------------------------------------- 1 | USE [DBAdmin] 2 | GO 3 | 4 | /****** Object: Table [dbo].[CheckIdentity] Script Date: 3/28/2016 10:24:52 AM ******/ 5 | SET ANSI_NULLS ON 6 | GO 7 | 8 | SET QUOTED_IDENTIFIER ON 9 | GO 10 | 11 | SET ANSI_PADDING ON 12 | GO 13 | 14 | IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CheckIdentity]') AND type IN (N'U')) 15 | BEGIN 16 | CREATE TABLE [dbo].[CheckIdentity]( 17 | [CheckIdentityID] [INT] IDENTITY(1,1) NOT NULL, 18 | [ServerName] [VARCHAR](64) NOT NULL, 19 | [DatabaseName] [VARCHAR](64) NOT NULL, 20 | [TableName] [VARCHAR](128) NOT NULL, 21 | [ColumnName] [VARCHAR](128) NOT NULL, 22 | [DataType] [VARCHAR](10) NOT NULL, 23 | [CurrentIdentityValue] [BIGINT] NOT NULL, 24 | [PercentageUsed] [DECIMAL](5, 2) NOT NULL, 25 | [CreatedDate] [DATETIME] NOT NULL CONSTRAINT [DF_CheckIdentity_CreatedDate] DEFAULT (GETDATE()), 26 | [CreatedBy] [VARCHAR](64) NOT NULL CONSTRAINT [DF_CheckIdentity_CreatedBy] DEFAULT (SUSER_NAME()), 27 | CONSTRAINT [PK_CheckIdentity_CheckIdentityID] PRIMARY KEY CLUSTERED 28 | ( 29 | [CheckIdentityID] ASC 30 | )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] 31 | ) ON [PRIMARY] 32 | END 33 | GO 34 | 35 | SET ANSI_PADDING OFF 36 | GO 37 | 38 | 39 | -------------------------------------------------------------------------------- /DBA Clean up MSDB Mail log and Backup History New.sql: -------------------------------------------------------------------------------- 1 | DECLARE @backupdate DATE = '2009-06-15' 2 | WHILE @backupdate < DATEADD(d, -30, @backupdate) 3 | BEGIN 4 | EXEC sp_delete_backuphistory @backupdate 5 | SELECT @backupdate = DATEADD(d, 15, @backupdate) 6 | END 7 | 8 | DECLARE @maildate DATE = '2009-06-15' 9 | WHILE @maildate < DATEADD(d, -14, GETDATE()) 10 | BEGIN 11 | EXEC msdb.dbo.sysmail_delete_mailitems_sp @sent_before = @maildate 12 | SELECT @maildate = DATEADD(d, 5, @maildate) 13 | END 14 | 15 | USE msdb 16 | go 17 | IF NOT EXISTS (SELECT * FROM sys.indexes WHERE OBJECT_ID = OBJECT_ID('[dbo].[backupset]') AND name = 'NCIX_BackupSet_BackupFinishDate_MediaSetID') 18 | CREATE NONCLUSTERED INDEX NCIX_BackupSet_BackupFinishDate_MediaSetID ON dbo.backupset(backup_finish_date) include (media_set_id) 19 | 20 | IF NOT EXISTS (SELECT * FROM sys.indexes WHERE OBJECT_ID = OBJECT_ID('[dbo].[backupset]') AND name = 'NCIX_BackupSet_BackupStartDate_MediaSetID') 21 | CREATE NONCLUSTERED INDEX NCIX_BackupSet_BackupStartDate_MediaSetID ON dbo.backupset(backup_start_date) include (media_set_id) 22 | 23 | 24 | 25 | 26 | 27 | 28 | DECLARE @DeleteDate DATE = '2011-10-01' 29 | WHILE @DeleteDate < DATEADD(d, -30, GETDATE()) 30 | BEGIN 31 | PRINT @DeleteDate 32 | DELETE FROM dbo.sysssislog 33 | WHERE endtime < @DeleteDate 34 | SELECT @DeleteDate = DATEADD(d, 5, @DeleteDate) 35 | END -------------------------------------------------------------------------------- /DBA Clean up MSDB Mail log and Backup History Newest.sql: -------------------------------------------------------------------------------- 1 | 2 | -- this deletes the backup history in msdb database 3 | -- link http://msdn.microsoft.com/en-us/library/ms188328.aspx 4 | USE msdb; 5 | GO 6 | -- Backup, maintenenace task cleanup 7 | DECLARE @DeleteBeforeDate DateTime 8 | SELECT @DeleteBeforeDate = DATEADD(DAY, DATEDIFF(DAY, 0, GetDate()) - 60, 0) 9 | --SELECT @DeleteBeforeDate 10 | 11 | 12 | -- Backup, maintenenace task cleanup 13 | EXEC sp_delete_backuphistory @oldest_date = @DeleteBeforeDate; 14 | EXEC sp_maintplan_delete_log @oldest_time= @DeleteBeforeDate; 15 | 16 | 17 | -- Mail item cleanup 18 | EXEC sysmail_delete_mailitems_sp @sent_before = @DeleteBeforeDate; 19 | EXEC sysmail_delete_log_sp @logged_before = @DeleteBeforeDate; 20 | -------------------------------------------------------------------------------- /DBA Cleanup Old Backup Files Using PowerShell.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/himadanreddy/SQL-DBA-SCRIPTS/3111841fe0efca6d018929c71d2201506912ddcb/DBA Cleanup Old Backup Files Using PowerShell.sql -------------------------------------------------------------------------------- /DBA Operator.sql: -------------------------------------------------------------------------------- 1 | USE [msdb] 2 | GO 3 | 4 | /****** Object: Operator [DBA Group] Script Date: 09/20/2011 10:12:36 ******/ 5 | EXEC msdb.dbo.sp_add_operator @name=N'DBA', 6 | @enabled=1, 7 | @weekday_pager_start_time=0, 8 | @weekday_pager_end_time=235959, 9 | @saturday_pager_start_time=0, 10 | @saturday_pager_end_time=235959, 11 | @sunday_pager_start_time=0, 12 | @sunday_pager_end_time=235959, 13 | @pager_days=127, 14 | @email_address=N'bulentgucuk@gmail.com', 15 | @category_name=N'[Uncategorized]' 16 | GO 17 | 18 | 19 | -------------------------------------------------------------------------------- /DBA WaitStat Collection 3 Create Jobs.sql: -------------------------------------------------------------------------------- 1 | SET NOCOUNT ON; 2 | DECLARE @ID BIGINT 3 | , @KeepLast BIGINT = 10000 4 | -- dbo.WaitingTasks cleanup 5 | SELECT @ID = MAX(WaitingTaskID) - @KeepLast 6 | FROM dbo.WaitingTasks WITH(NOLOCK); 7 | 8 | DELETE FROM dbo.WaitingTasks 9 | WHERE WaitingTaskID < @ID; 10 | 11 | -- dbo.Waits cleanup 12 | SELECT @ID = MAX(WaitID) - @KeepLast 13 | FROM dbo.Waits WITH(NOLOCK); 14 | 15 | DELETE FROM dbo.Waits 16 | WHERE WaitID < @ID; 17 | 18 | -- dbo.WhoIsActive cleanup 19 | SELECT @ID = MAX(RowId)- @KeepLast 20 | FROM dbo.WhoIsActive WITH(NOLOCK); 21 | 22 | DELETE FROM dbo.WhoIsActive 23 | WHERE RowId < @ID; 24 | 25 | -- dbo.DatabaseFileLatency cleanup 26 | SELECT @ID = MAX(RowId)- @KeepLast 27 | FROM dbo.DatabaseFileLatency WITH(NOLOCK); 28 | 29 | DELETE FROM dbo.DatabaseFileLatency 30 | WHERE RowId < @ID; -------------------------------------------------------------------------------- /DBCC CheckDB for All DBs.sql: -------------------------------------------------------------------------------- 1 | --runs DBCC checkdb against ALL databases on a server 2 | --Needs to be run against master database i.e. that is where sp_MSForEachdb is found 3 | --To exclude a database add the database name to the NOT IN list in @cmd1 4 | DECLARE @cmd1 VARCHAR(500) 5 | 6 | 7 | SET @cmd1 = 'if ''?'' NOT IN (''tempdb'') DBCC CHECKDB([?[) WITH NO_INFOMSGS' 8 | EXEC sp_MSforeachdb @command1 = @cmd1 -------------------------------------------------------------------------------- /DBCC PAGE sample.sql: -------------------------------------------------------------------------------- 1 | USE Ducks_Integration; 2 | GO 3 | 4 | -- PAGE CONTENT 5 | DBCC PAGE (36, 1, 1950432,3); 6 | 7 | -- PAGE METADATA 8 | DBCC TRACEON (3604); 9 | DBCC PAGE (36, 1, 1950432,0); 10 | DBCC TRACEOFF (3604); 11 | GO 12 | 13 | --https://www.sqlskills.com/blogs/paul/finding-table-name-page-id/ -------------------------------------------------------------------------------- /DataCollectorCounterDataDetailsQuery_Ch05_DataCollector.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/himadanreddy/SQL-DBA-SCRIPTS/3111841fe0efca6d018929c71d2201506912ddcb/DataCollectorCounterDataDetailsQuery_Ch05_DataCollector.sql -------------------------------------------------------------------------------- /Database IO Report.sql: -------------------------------------------------------------------------------- 1 | 2 | 3 | -- total read and write activities by database 4 | select db_name(mf.database_id) as database_name, mf.physical_name, 5 | left(mf.physical_name, 1) as drive_letter, 6 | vfs.num_of_writes, vfs.num_of_bytes_written, vfs.io_stall_write_ms, 7 | mf.type_desc, vfs.num_of_reads, vfs.num_of_bytes_read, vfs.io_stall_read_ms, 8 | vfs.io_stall, vfs.size_on_disk_bytes 9 | from sys.master_files mf 10 | join sys.dm_io_virtual_file_stats(NULL, NULL) vfs 11 | on mf.database_id=vfs.database_id and mf.file_id=vfs.file_id 12 | order by vfs.num_of_bytes_written desc 13 | 14 | 15 | -- total read and write activities of a logical drive 16 | select left(mf.physical_name, 1) as drive_letter, sample_ms, 17 | sum(vfs.num_of_writes) as total_num_of_writes, 18 | sum(vfs.num_of_bytes_written) as total_num_of_bytes_written, 19 | sum(vfs.io_stall_write_ms) as total_io_stall_write_ms, 20 | sum(vfs.num_of_reads) as total_num_of_reads, 21 | sum(vfs.num_of_bytes_read) as total_num_of_bytes_read, 22 | sum(vfs.io_stall_read_ms) as total_io_stall_read_ms, 23 | sum(vfs.io_stall) as total_io_stall, 24 | sum(vfs.size_on_disk_bytes) as total_size_on_disk_bytes 25 | from sys.master_files mf 26 | join sys.dm_io_virtual_file_stats(NULL, NULL) vfs 27 | on mf.database_id=vfs.database_id and mf.file_id=vfs.file_id 28 | group by left(mf.physical_name, 1), sample_ms 29 | -------------------------------------------------------------------------------- /Days Since the Job Run.sql: -------------------------------------------------------------------------------- 1 | select MAX(DATEDIFF(dd, CONVERT(datetime, CAST(SJH.[run_date] AS CHAR(8)), 101), GETDATE())) AS [Days Since Last Run] 2 | FROM msdb.dbo.[sysjobhistory] SJH INNER JOIN [msdb].dbo.[sysjobs] SJ ON SJH.[job_id] = SJ.[job_id] 3 | WHERE SJH.[step_id] = 0 4 | GROUP BY SJ.[name] 5 | ORDER BY SJ.[name] -------------------------------------------------------------------------------- /DefaultTraceQueries&Activity_Ch05_DefaultTrace.sql: -------------------------------------------------------------------------------- 1 | /*The following queries from Healthy SQL Chapter 5-Tools Of The Trade 2 | Default Trace >> Ensure Default Trace Is On section 3 | Run these separately as needed */ 4 | 5 | -- Check if Default Trace is Enabled/On 6 | SELECT name, CASE WHEN value_in_use=1 THEN 'ENABLED' 7 | WHEN value_in_use=0 THEN 'DISABLED' 8 | END AS [status] 9 | FROM sys.configurations 10 | WHERE name='default trace enabled' 11 | 12 | GO 13 | 14 | --List Events Captured By The Default Trace 15 | declare @handle int = (select id from sys.traces where is_default = 1); 16 | -- or use where id=@traceid 17 | select distinct e.eventid, n.name from 18 | fn_trace_geteventinfo(@handle) e 19 | join sys.trace_events n 20 | on e.eventid = n.trace_event_id 21 | order by n.name asc 22 | 23 | GO 24 | 25 | --Get Active Default Trace Path on you SQL Server 26 | declare @trcpath varchar(255) 27 | select @trcpath=convert(varchar(255),value) from [fn_trace_getinfo](NULL) 28 | where [property] = 2 AND traceid=1 29 | select @trcpath As ActiveDefaultTracePath 30 | -- Use fn_trace_gettable to return system trace data 31 | SELECT name, EventClass, category_id, substring(TextData,1,50), Error, DatabaseName, 32 | ApplicationName,LoginName,SPID,StartTime,ObjectName 33 | FROM [fn_trace_gettable]('' + @trcpath + '', DEFAULT) t 34 | inner join sys.trace_events te 35 | on t.EventClass=te.trace_event_id 36 | ORDER BY StartTime; -------------------------------------------------------------------------------- /Delete Duplicate Rows With CTE.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE dbo.DuplicateRcordTable (Col1 INT, Col2 INT, Col3 VARCHAR(20)) 2 | INSERT INTO DuplicateRcordTable 3 | SELECT 1, 1,'USA' 4 | UNION ALL 5 | SELECT 1, 1, 'USA' --duplicate 6 | UNION ALL 7 | SELECT 1, 1, 'USA' --duplicate 8 | UNION ALL 9 | SELECT 1, 2, 'UK' 10 | UNION ALL 11 | SELECT 1, 2, 'UK' --duplicate 12 | UNION ALL 13 | SELECT 1, 3, 'FR' 14 | UNION ALL 15 | SELECT 1, 4, 'SP' 16 | GO 17 | 18 | /* It should give you 7 rows */ 19 | SELECT * 20 | FROM DuplicateRcordTable 21 | GO 22 | 23 | /* Delete Duplicate records */ 24 | WITH CTE (COl1,Col2, DuplicateCount) 25 | AS 26 | ( 27 | SELECT COl1,Col2, 28 | ROW_NUMBER() OVER(PARTITION BY COl1,Col2 ORDER BY Col1) AS DuplicateCount 29 | FROM DuplicateRcordTable 30 | ) 31 | DELETE 32 | FROM CTE 33 | WHERE DuplicateCount > 1 34 | 35 | GO 36 | 37 | SELECT * 38 | FROM DuplicateRcordTable 39 | GO 40 | DROP TABLE dbo.DuplicateRcordTable -------------------------------------------------------------------------------- /Delete Old backups.txt: -------------------------------------------------------------------------------- 1 | $Path = "E:\SQLServer\backup" 2 | 3 | $Daysback = "-5" 4 | 5 | $CurrentDate = Get-Date 6 | 7 | $DatetoDelete = $CurrentDate.AddDays($Daysback) 8 | 9 | Get-ChildItem $Path -Recurse -include *.txt, *.bak| Where-Object { $_.LastWriteTime -lt $DatetoDelete } | Remove-Item 10 | -------------------------------------------------------------------------------- /DeleteAllDataInDB.sql: -------------------------------------------------------------------------------- 1 | --TRUNCATE TABLE on stand-alone and child tables, or DELETE if it's a parent table: 2 | 3 | -- disable referential integrity 4 | EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL' 5 | GO 6 | 7 | EXEC sp_MSForEachTable ' 8 | IF OBJECTPROPERTY(object_id(''?''), ''TableHasForeignRef'') = 1 9 | DELETE FROM ? 10 | else 11 | TRUNCATE TABLE ? 12 | ' 13 | GO 14 | 15 | -- enable referential integrity again 16 | EXEC sp_MSForEachTable 'ALTER TABLE ? CHECK CONSTRAINT ALL' 17 | GO 18 | 19 | -------------------------------------------------------------------------------- /DesignQueryForCustomReportWaitStats_Ch08_CreateTheDataSets.sql: -------------------------------------------------------------------------------- 1 | SELECT [wait_type] 2 | ,[WaitSec] 3 | /* ,[ResourceSec] 4 | ,[SignalSec] 5 | ,[WaitCount] 6 | ,[AvgWait_Sec] 7 | ,[AvgRes_Sec] 8 | ,[AvgSig_Sec] */ -- you only need WaitSec, Percentage & CaptureDate 9 | ,[Percentage] 10 | ,[CaptureDate] 11 | FROM [dbo].[waitstats] 12 | /*Where CaptureDate between @BeginDate AND @EndDate 13 | AND (@WaitType= 'ALL' 14 | OR [Wait_type] in (@WaitType) )*/ --REMOVE COMMENTS AFTER PARAMS ARE CREATED -------------------------------------------------------------------------------- /Disable Enable FK.sql: -------------------------------------------------------------------------------- 1 | 2 | DECLARE @RowId INT, 3 | @Str VARCHAR(512) 4 | 5 | DECLARE @DisableFK TABLE ( 6 | RowId INT IDENTITY(1,1), 7 | FKName VARCHAR(255) NOT NULL, 8 | FKTableName VARCHAR(100) NOT NULL, 9 | ReferencedTable VARCHAR(100) NOT NULL, 10 | Is_Disabled BIT NOT NULL 11 | ) 12 | INSERT INTO @DisableFK 13 | SELECT Name AS FKName, 14 | OBJECT_NAME(Parent_Object_id) AS FKTableName, 15 | OBJECT_NAME(Referenced_Object_id) AS ReferencedTable, 16 | Is_Disabled 17 | FROM SYS.FOREIGN_KEYS 18 | WHERE OBJECT_NAME(Referenced_Object_id) = 'Applications' 19 | ORDER BY OBJECT_NAME(Parent_Object_id) 20 | 21 | SELECT @RowId = MAX(RowId) FROM @DisableFK 22 | 23 | WHILE @RowId > 0 24 | BEGIN 25 | SELECT @Str = '' 26 | SELECT @Str = 'ALTER TABLE ' + FKTableName + ' NOCHECK CONSTRAINT ' + FKName -- Disable foreign key constraint 27 | --SELECT @Str = 'ALTER TABLE ' + FKTableName + ' CHECK CONSTRAINT ' + FKName -- Enable foreign key constraint 28 | FROM @DisableFK 29 | WHERE RowId = @RowId 30 | 31 | PRINT @Str 32 | --EXEC (@Str) 33 | UPDATE @DisableFK 34 | SET Is_Disabled = 1 35 | WHERE RowId = @RowId 36 | SELECT @RowId = @RowId - 1 37 | END 38 | 39 | SELECT * FROM @DisableFK 40 | -------------------------------------------------------------------------------- /Disable Publishing Distribution.sql: -------------------------------------------------------------------------------- 1 | use [master] 2 | exec sp_dropdistributor @no_checks = 1 3 | GO 4 | -------------------------------------------------------------------------------- /DriveFreeSpace.sql: -------------------------------------------------------------------------------- 1 | SET NOCOUNT ON 2 | DECLARE @hr int 3 | DECLARE @fso int 4 | DECLARE @size float 5 | DECLARE @mbtotal int 6 | DECLARE @drive char(1) 7 | DECLARE @fso_Method varchar(255) 8 | SET @mbTotal = 0 9 | 10 | CREATE TABLE Tempdb.dbo.Drvspace (drive char(1), mbfree int, mbtotalSpace int) 11 | INSERT INTO Tempdb.dbo.Drvspace (drive, mbfree) EXEC master.dbo.xp_fixeddrives 12 | 13 | EXEC @hr = master.dbo.sp_OACreate 'Scripting.FilesystemObject', @fso OUTPUT 14 | 15 | DECLARE cDrives CURSOR FAST_FORWARD FOR SELECT drive FROM Tempdb.dbo.Drvspace 16 | OPEN cDrives 17 | FETCH NEXT FROM cDrives INTO @drive 18 | 19 | WHILE @@FETCH_STATUS = 0 20 | BEGIN 21 | SET @fso_Method = 'Drives("' + @drive + ':").TotalSize' 22 | EXEC @hr = sp_OAMethod @fso, @fso_method, @size OUTPUT 23 | 24 | update Tempdb.dbo.Drvspace set mbtotalSpace = @size/(1024*1024) 25 | where drive = @drive 26 | FETCH NEXT FROM cDrives INTO @drive 27 | END 28 | CLOSE cDrives 29 | DEALLOCATE cDrives 30 | EXEC @hr = sp_OADestroy @fso 31 | 32 | 33 | 34 | select * from Tempdb.dbo.Drvspace 35 | drop table Tempdb.dbo.Drvspace -------------------------------------------------------------------------------- /Drop Clean Buffers and Free Proc Cache.sql: -------------------------------------------------------------------------------- 1 | USE MASTER; 2 | GO 3 | CHECKPOINT; 4 | GO 5 | DBCC DROPCLEANBUFFERS; 6 | GO 7 | DBCC FREEPROCCACHE; 8 | GO 9 | DBCC FREESYSTEMCACHE ('ALL'); 10 | GO 11 | DBCC FREESESSIONCACHE; 12 | GO -------------------------------------------------------------------------------- /Drop FK Constraint.sql: -------------------------------------------------------------------------------- 1 | -- drop all FK constraints 2 | declare @cnt int, 3 | @sql Varchar(1000), 4 | @rowcount int 5 | 6 | create table #test ( 7 | id int identity, 8 | line Varchar(1000) 9 | ) 10 | insert into #test(line) 11 | select 'alter table ' + 12 | quotename(schema_name(fk.schema_id)) + '.' + 13 | quotename(OBJECT_NAME(fk.parent_object_id)) + ' drop constraint ' + 14 | quotename(fk.name) 15 | --,fk.* 16 | from sys.foreign_keys as fk 17 | inner join sys.objects as o 18 | on fk.referenced_object_id = o.object_id 19 | where o.is_ms_shipped = 0 20 | 21 | select @rowcount = @@rowcount 22 | select @cnt = 1 23 | while @rowcount > = @cnt 24 | begin 25 | select @sql = line from #test where id = @cnt 26 | print @sql 27 | exec (@sql) 28 | select @cnt= @cnt+ 1 29 | end 30 | drop table #test 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /Drop Restored Copy of Replicated Database.sql: -------------------------------------------------------------------------------- 1 | 2 | 3 | *** Backup and Restore Replicated db and try to drop it if not run the following statement. 4 | USE MASTER EXEC dbo.sp_removedbreplication @dbname = 'MyDatabase' -------------------------------------------------------------------------------- /Drop Server Name and Add Builtin Admin Group To SysAdmin.sql: -------------------------------------------------------------------------------- 1 | USE [master] 2 | --check the server names 3 | --SELECT * FROM SYS.SERVERS 4 | GO 5 | 6 | -- Drop the original image of the windows server 7 | EXEC SP_DROPSERVER @@SERVERNAME 8 | 9 | GO 10 | 11 | -- Add the new windows netbios server name as local server 12 | DECLARE @Servername SYSNAME 13 | 14 | SELECT @Servername = CAST(SERVERPROPERTY('ComputerNamePhysicalNetBIOS') AS SYSNAME) 15 | 16 | IF NOT EXISTS ( 17 | SELECT * 18 | FROM sys.servers 19 | WHERE is_linked = 0 20 | ) 21 | BEGIN 22 | EXEC SP_ADDSERVER @servername, @local = 'Local' 23 | END 24 | 25 | GO 26 | 27 | -- Add builtin adminstrators group as sysadmin 28 | 29 | IF NOT EXISTS ( 30 | SELECT * 31 | FROM SYS.server_principals 32 | WHERE name = 'BUILTIN\administrators' 33 | ) 34 | BEGIN 35 | CREATE LOGIN [BUILTIN\administrators] FROM WINDOWS WITH DEFAULT_DATABASE=[master], DEFAULT_LANGUAGE=[us_english]; 36 | END 37 | 38 | 39 | IF NOT EXISTS ( 40 | SELECT SRM.role_principal_id, SP.name AS Role_Name, SRM.member_principal_id, SP2.name AS Member_Name 41 | FROM sys.server_role_members AS SRM 42 | INNER JOIN sys.server_principals AS SP 43 | ON SRM.Role_principal_id = SP.principal_id 44 | INNER JOIN sys.server_principals AS SP2 45 | ON SRM.member_principal_id = SP2.principal_id 46 | WHERE SP.name = 'sysadmin' 47 | AND sp2.name = 'BUILTIN\administrators' 48 | ) 49 | BEGIN 50 | EXEC master..sp_addsrvrolemember @loginame = N'BUILTIN\administrators', @rolename = N'sysadmin'; 51 | END 52 | -------------------------------------------------------------------------------- /Drop Views and Tables.sql: -------------------------------------------------------------------------------- 1 | -- drop all the views 2 | declare @cnt int, 3 | @sql Varchar(1000), 4 | @rowcount int 5 | 6 | create table #test ( 7 | id int identity, 8 | line Varchar(1000) 9 | ) 10 | insert into #test(line) 11 | select 'drop view ' + 12 | QUOTENAME(SCHEMA_NAME(schema_id)) + '.' + 13 | QUOTENAME(name) 14 | from sys.views 15 | where is_ms_shipped = 0 16 | 17 | 18 | select @rowcount = @@rowcount 19 | select @cnt = 1 20 | while @rowcount > = @cnt 21 | begin 22 | select @sql = line from #test where id = @cnt 23 | print @sql 24 | exec (@sql) 25 | select @cnt= @cnt+ 1 26 | end 27 | drop table #test 28 | 29 | go 30 | 31 | -- drop all the tables 32 | declare @cnt int, 33 | @sql Varchar(1000), 34 | @rowcount int 35 | 36 | create table #test ( 37 | id int identity, 38 | line Varchar(1000) 39 | ) 40 | insert into #test(line) 41 | select 'drop table ' + 42 | QUOTENAME(SCHEMA_NAME(schema_id)) + '.' + 43 | QUOTENAME(name) 44 | from sys.tables 45 | where is_ms_shipped = 0 46 | 47 | 48 | select @rowcount = @@rowcount 49 | select @cnt = 1 50 | while @rowcount > = @cnt 51 | begin 52 | select @sql = line from #test where id = @cnt 53 | print @sql 54 | exec (@sql) 55 | select @cnt= @cnt+ 1 56 | end 57 | drop table #test 58 | 59 | -------------------------------------------------------------------------------- /DropConstraintDynamic.sql: -------------------------------------------------------------------------------- 1 | -- Drop Constraint Dynamic 2 | declare @ConstraintToBeDropped varchar (100), 3 | @Sql varchar (1000) 4 | -- get the constraint name 5 | select @ConstraintToBeDropped = Constraint_Name 6 | from information_schema.key_column_usage 7 | where table_name = 'VisitorPageHits' 8 | and column_name = 'pageid' 9 | 10 | -- assign value to dynamic sql statement 11 | select @Sql = 'alter table dbo.visitorpagehits drop constraint ' + @ConstraintToBeDropped 12 | 13 | -- execute and drop the constraint 14 | print @sql 15 | exec (@sql) -------------------------------------------------------------------------------- /DumpTopWaitsToHistoryWaitsTable_Chap03_SlowPerformance.sql: -------------------------------------------------------------------------------- 1 | SELECT *, getdate() as ArchiveDate 2 | 3 | INTO Wait_Stats_History 4 | 5 | FROM Sys.dm_os_wait_stats 6 | 7 | WHERE wait_type NOT IN 8 | 9 | ('CLR_SEMAPHORE','LAZYWRITER_SLEEP','RESOURCE_QUEUE','SLEEP_TASK' 10 | 11 | ,'SLEEP_SYSTEMTASK','SQLTRACE_BUFFER_FLUSH','WAITFOR', 'LOGMGR_QUEUE','CHECKPOINT_QUEUE' 12 | 13 | ,'REQUEST_FOR_DEADLOCK_SEARCH','XE_TIMER_EVENT','BROKER_TO_FLUSH','BROKER_TASK_STOP','CLR_MANUAL_EVENT' 14 | 15 | ,'CLR_AUTO_EVENT','DISPATCHER_QUEUE_SEMAPHORE', 'FT_IFTS_SCHEDULER_IDLE_WAIT' 16 | 17 | ,'XE_DISPATCHER_WAIT', 'XE_DISPATCHER_JOIN', 'SQLTRACE_INCREMENTAL_FLUSH_SLEEP') -------------------------------------------------------------------------------- /Enable Query Store.sql: -------------------------------------------------------------------------------- 1 | USE [master] 2 | GO 3 | 4 | --https://www.sqlskills.com/blogs/erin/query-store-settings/ 5 | --SQL Server 2016 & 2017 6 | ALTER DATABASE [ChicagoBulls] SET QUERY_STORE = ON; 7 | GO 8 | 9 | ALTER DATABASE [ChicagoBulls] 10 | SET QUERY_STORE (OPERATION_MODE = READ_WRITE, 11 | QUERY_CAPTURE_MODE = AUTO, 12 | MAX_PLANS_PER_QUERY = 200, 13 | MAX_STORAGE_SIZE_MB = 128, 14 | CLEANUP_POLICY = (STALE_QUERY_THRESHOLD_DAYS = 30), 15 | SIZE_BASED_CLEANUP_MODE = AUTO, 16 | DATA_FLUSH_INTERVAL_SECONDS = 900, 17 | INTERVAL_LENGTH_MINUTES = 60 18 | ); 19 | GO 20 | -------------------------------------------------------------------------------- /Estimate Compression Savings.sql: -------------------------------------------------------------------------------- 1 | EXEC sp_estimate_data_compression_savings 'dbo', 'VisitorPageHits', NULL, NULL, 'PAGE' ; 2 | GO 3 | 4 | 5 | EXEC sp_estimate_data_compression_savings 'dbo', 'VisitorPageHits', NULL, NULL, 'ROW' ; 6 | GO 7 | 8 | /**** 9 | 10 | [dbo].[VisitorSessions] 11 | 12 | 13 | 14 | ***/ -------------------------------------------------------------------------------- /FK Drop Statement Execute From Stored Table.sql: -------------------------------------------------------------------------------- 1 | ------------------------------------------------------------------------ 2 | -- 3 | -- This job step drop foreign key constraints to make data purging easier.. 4 | -- 5 | ------------------------------------------------------------------------ 6 | USE NetQuoteDevCut 7 | SET NOCOUNT ON 8 | -- DROP FK CONSTRAINTS 9 | DECLARE @MaxFKid INT, 10 | @Str VARCHAR(1024) 11 | 12 | SELECT @MaxFKid = MAX(FKid) 13 | FROM dbo.FKDrop 14 | 15 | WHILE @MaxFKid > 0 16 | BEGIN 17 | SELECT @Str = '' 18 | SELECT @Str = [Str] 19 | FROM dbo.FKDrop 20 | WHERE FKid = @MaxFKid 21 | PRINT @Str 22 | EXEC (@Str) 23 | SELECT @MaxFKid = @MaxFKid - 1 24 | END -------------------------------------------------------------------------------- /Find Active Cluster Node.sql: -------------------------------------------------------------------------------- 1 | 2 | -- FIND ACTIVE CLUSTER NODE NAME IN SQL SERVER CLUSTER 3 | SELECT CAST(SERVERPROPERTY('ComputerNamePhysicalNetBIOS') AS VARCHAR(50)) 4 | AS PhysicalServerName -------------------------------------------------------------------------------- /Find Active Sessions.sql: -------------------------------------------------------------------------------- 1 | -- Find Active Sessions 2 | SELECT 3 | r.session_id 4 | , r.blocking_session_id 5 | , s.program_name 6 | , s.host_name 7 | , s.login_name 8 | , s.login_time 9 | , t.text 10 | 11 | FROM sys.dm_exec_requests AS r 12 | INNER JOIN sys.dm_exec_sessions AS s on r.session_id = s.session_id 13 | CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) AS t 14 | 15 | WHERE s.is_user_process = 1 16 | AND r.session_id <> @@SPID -- NOT MY SPID RUNNING THIS QUERY 17 | --AND s.login_name = 'NQCORP\ChappellO' -------------------------------------------------------------------------------- /Find Active Transactions and Execution Plans.sql: -------------------------------------------------------------------------------- 1 | -- Find Active Transactions and Execution Plans 2 | SELECT s_tst.[session_id], 3 | s_es.[login_name] AS [Login Name], 4 | S_tdt.[database_transaction_begin_time] AS [Begin Time], 5 | s_tdt.[database_transaction_log_record_count] AS [Log Records], 6 | s_tdt.[database_transaction_log_bytes_used] AS [Log Bytes], 7 | s_tdt.[database_transaction_log_bytes_reserved] AS [Log Reserved], 8 | s_est.[text] AS [Last T-SQL Text], 9 | s_eqp.[query_plan] AS [Last Query Plan] 10 | FROM sys.dm_tran_database_transactions s_tdt 11 | JOIN sys.dm_tran_session_transactions s_tst 12 | ON s_tst.[transaction_id] = s_tdt.[transaction_id] 13 | JOIN sys.[dm_exec_sessions] s_es 14 | ON s_es.[session_id] = s_tst.[session_id] 15 | JOIN sys.dm_exec_connections s_ec 16 | ON s_ec.[session_id] = s_tst.[session_id] 17 | LEFT OUTER JOIN sys.dm_exec_requests s_er 18 | ON s_er.[session_id] = s_tst.[session_id] 19 | CROSS APPLY sys.dm_exec_sql_text (s_ec.[most_recent_sql_handle]) AS s_est 20 | OUTER APPLY sys.dm_exec_query_plan (s_er.[plan_handle]) AS s_eqp 21 | ORDER BY [Begin Time] ASC; 22 | GO -------------------------------------------------------------------------------- /Find Actively Running SQL Server Agent Jobs.sql: -------------------------------------------------------------------------------- 1 | USE msdb; 2 | GO 3 | SELECT 4 | j.name AS job_name, 5 | ja.start_execution_date, 6 | ISNULL(last_executed_step_id,0)+1 AS current_executed_step_id, 7 | Js.step_name 8 | FROM dbo.sysjobactivity AS ja 9 | LEFT OUTER JOIN dbo.sysjobhistory AS jh ON ja.job_history_id = jh.instance_id 10 | INNER JOIN dbo.sysjobs AS j ON ja.job_id = j.job_id 11 | INNER JOIN dbo.sysjobsteps AS js ON ja.job_id = js.job_id AND ISNULL(ja.last_executed_step_id,0)+1 = js.step_id 12 | WHERE ja.session_id = (SELECT TOP 1 session_id FROM msdb.dbo.syssessions ORDER BY agent_start_date DESC) 13 | AND ja.start_execution_date is not null 14 | AND ja.stop_execution_date is null 15 | --AND j.name = 'NameOfTheJob' -- Uncomment and supply the name of the job you need to find out if it's actively running 16 | GO -------------------------------------------------------------------------------- /Find Ad Hoc Related Plan Cache numbers.sql: -------------------------------------------------------------------------------- 1 | /*** 2 | DBCC FREEproccache 3 | 4 | EXEC sp_configure 'optimize for ad hoc workloads', 0 5 | RECONFIGURE 6 | GO 7 | 8 | **/ 9 | 10 | --Gives you the total number of one-time use ad hoc queries currently in the 11 | --plan cache. 12 | USE master 13 | GO 14 | SELECT SUM(CASE WHEN usecounts = 1 THEN 1 15 | ELSE 0 16 | END) AS [Adhoc Plans Use Count of 1] 17 | FROM sys.dm_exec_cached_plans 18 | WHERE objtype = 'Adhoc' 19 | GROUP BY objtype; 20 | GO 21 | 22 | --List all the one-time ad hoc queries, row by row, currently in the plan 23 | --cache. 24 | USE master 25 | GO 26 | SELECT usecounts , 27 | size_in_bytes , 28 | cacheobjtype , 29 | objtype 30 | FROM sys.dm_exec_cached_plans 31 | WHERE objtype = 'Adhoc' 32 | AND usecounts = 1 33 | ORDER BY size_in_bytes desc 34 | GO 35 | 36 | --Tells you how much memory is being used by the one-time use ad hoc queries 37 | USE master 38 | GO 39 | SELECT SUM(CAST(( CASE WHEN usecounts = 1 THEN size_in_bytes 40 | ELSE 0 41 | END ) AS DECIMAL(18, 2))) / 1024 / 1024 AS [Total MBs Used by Adhoc Plans With Use Count of 1] 42 | FROM sys.dm_exec_cached_plans 43 | WHERE objtype = 'Adhoc' 44 | GROUP BY objtype; 45 | GO -------------------------------------------------------------------------------- /Find All Objects in All User Databases Using Name Like.sql: -------------------------------------------------------------------------------- 1 | -- Find object name exist in user databases 2 | SET NOCOUNT ON; 3 | DECLARE @ObjectName VARCHAR(128) = '%account%', 4 | @str varchar(2048), 5 | @rowid TINYINT, 6 | @DBname VARCHAR(128); 7 | 8 | -- Table variable to loop user databases 9 | DECLARE @d TABLE (rowid TINYINT IDENTITY, 10 | DbName sysname 11 | ) 12 | 13 | INSERT INTO @d (DbName) 14 | SELECT name FROM sys.databases 15 | WHERE database_id > 4 16 | ORDER BY name DESC; 17 | 18 | -- Temp table to store the objects 19 | IF OBJECT_ID('Tempdb..#o') IS NOT NULL 20 | BEGIN 21 | DROP TABLE #o; 22 | END 23 | CREATE TABLE #o (Rowid SMALLINT IDENTITY, 24 | DbName sysname, 25 | SchemaName sysname NULL, 26 | ObjectName sysname, 27 | Type_Desc VARCHAR(128), 28 | Create_Date DATETIME, 29 | Modify_Date DATETIME, 30 | is_published BIT 31 | ); 32 | SELECT @rowid = MAX(rowid) 33 | FROM @d; WHILE @rowid > 0 34 | BEGIN 35 | SELECT @DBname = DbName 36 | FROM @d 37 | WHERE rowid = @rowid SELECT @str = 'USE ' + @DBname + CHAR(13) SELECT @str = @str + 'INSERT INTO #o' + CHAR(13) SELECT @str = @str + 'SELECT ' + '''' + @DBname + '''' + ' AS DbName, SCHEMA_NAME(schema_id) AS SchemaName,name AS ObjectName,type_desc, create_date, modify_date,is_published' + CHAR(13) SELECT @str = @str + 'FROM sys.objects WHERE NAME LIKE ' + '''' + @ObjectName + '''' --PRINT @str 38 | EXEC (@STR); 39 | 40 | SET @rowid = @rowid - 1 41 | END 42 | 43 | SELECT * FROM #o --WHERE Type_Desc = 'USER_TABLE' DROP TABLE #o; -------------------------------------------------------------------------------- /Find All The Schemas Tables Columns and DataTypes.sql: -------------------------------------------------------------------------------- 1 | -- Find all The Schemas, Tables, Columns, and Column DataTypes 2 | SELECT s.name AS SchemaName, 3 | t.name AS TableName, 4 | c.name AS ColumnName, 5 | t1.name AS DataType, 6 | CASE 7 | WHEN c.system_type_id = 231 THEN c.max_length/2 8 | ELSE c.max_length 9 | END AS MaxLength, 10 | c.is_nullable AS IsNullable 11 | --,c.* 12 | FROM sys.tables AS t 13 | INNER JOIN sys.schemas AS S 14 | ON s.schema_id = t.schema_id 15 | INNER JOIN sys.columns AS c 16 | ON c.object_id = t.object_id 17 | INNER JOIN sys.types AS t1 18 | ON t1.system_type_id = c.system_type_id 19 | WHERE is_ms_shipped = 0 20 | ORDER BY s.name, t.name -------------------------------------------------------------------------------- /Find All User Created Objects.sql: -------------------------------------------------------------------------------- 1 | 2 | 3 | -- find all the user created objects 4 | SELECT QUOTENAME(DB_NAME(database_id)) 5 | + N'.' 6 | + QUOTENAME(OBJECT_SCHEMA_NAME(object_id, database_id)) 7 | + N'.' 8 | + QUOTENAME(OBJECT_NAME(object_id, database_id)) 9 | , * 10 | FROM sys.dm_db_index_operational_stats(5, null, null, null) -- CHENGE THE DB_ID 11 | WHERE OBJECT_ID > 100 12 | ORDER BY PAGE_LATCH_WAIT_COUNT DESC, 13 | PAGE_LATCH_WAIT_IN_MS DESC 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /Find Authentication Scheme And Net Transport.sql: -------------------------------------------------------------------------------- 1 | Select 2 | s.session_id, 3 | s.login_name, 4 | s.host_name, 5 | c.auth_scheme, 6 | c.net_transport, 7 | c.connect_time 8 | from sys.dm_exec_connections c 9 | inner join sys.dm_exec_sessions s 10 | on c.session_id = s.session_id 11 | where s.session_id = @@SPID 12 | order by s.login_name 13 | 14 | -------------------------------------------------------------------------------- /Find Availability Group Health Secondary Node.sql: -------------------------------------------------------------------------------- 1 | USE master; 2 | SET NOCOUNT ON; 3 | SELECT TOP 1 4 | cn.node_name 5 | --, rs.role_desc 6 | --, rs.synchronization_health 7 | --, rs.synchronization_health_desc 8 | --, cs.replica_server_name 9 | --, rs.role 10 | FROM sys.dm_hadr_availability_replica_states AS RS 11 | INNER JOIN sys.dm_hadr_availability_replica_cluster_states AS CS ON rs.replica_id = cs.replica_id 12 | INNER JOIN sys.dm_hadr_availability_replica_cluster_nodes AS CN ON cs.replica_server_name = CN.replica_server_name 13 | WHERE rs.role = 2 14 | AND rs.synchronization_health = 2; 15 | -------------------------------------------------------------------------------- /Find Avg Space Used Page Count and Avg Record Size Per Index For Table.sql: -------------------------------------------------------------------------------- 1 | -- Find Avg Fragmentation, Page Count and Avg record size Per Index 2 | 3 | -- alter index PK_PAYLOAD_STAGING on INSTRUMENTATION.PayloadStaging rebuild --with (online = on) 4 | 5 | -- took 27 seconds to rebuild offline (xml datatype) on sqlclr01-d 6 | -- took 22 seconds to rebuild offline (xml datatype) on sqlclr03-p 7 | 8 | DECLARE @db_id SMALLINT; 9 | DECLARE @object_id INT; 10 | 11 | SET @db_id = DB_ID(N'SOCPLATFORM_QA'); 12 | SET @object_id = OBJECT_ID(N'INSTRUMENTATION.PayloadStaging'); 13 | 14 | 15 | SELECT 16 | db_name(database_id) AS DatabaseName, 17 | object_name(object_id) AS ObjectName, 18 | Index_Id, 19 | Partition_Number, 20 | Index_Type_Desc, 21 | Alloc_Unit_type_desc, 22 | Index_Depth, 23 | Index_Level, 24 | 25 | avg_page_space_used_in_percent 26 | ,avg_fragmentation_in_percent 27 | ,avg_fragment_size_in_pages 28 | ,record_count 29 | ,page_count 30 | ,fragment_count 31 | ,avg_record_size_in_bytes 32 | ,min_record_size_in_bytes 33 | ,max_record_size_in_bytes 34 | FROM sys.dm_db_index_physical_stats(@db_id,@object_id,null,NULL,'DETAILED') 35 | GO 36 | 37 | -------------------------------------------------------------------------------- /Find Batch Requests Compilations and Plan ReUse.sql: -------------------------------------------------------------------------------- 1 | select t1.cntr_value As [Batch Requests/sec] 2 | ,t2.cntr_value As [SQL Compilations/sec] 3 | , plan_reuse_percentage =convert(decimal(15,2) 4 | , (t1.cntr_value*1.0-t2.cntr_value*1.0)/t1.cntr_value*100) 5 | from master.sys.dm_os_performance_counters t1, 6 | master.sys.dm_os_performance_counters t2 7 | where t1.counter_name='Batch Requests/sec' 8 | and t2.counter_name='SQL Compilations/sec' -------------------------------------------------------------------------------- /Find Block Size of the Volumes.sql: -------------------------------------------------------------------------------- 1 | --Enable xp_cmdshell 2 | EXEC sp_configure 'show advanced options', 1 3 | RECONFIGURE 4 | EXEC sp_configure 'xp_cmdshell', 1 5 | RECONFIGURE 6 | GO 7 | 8 | CREATE TABLE #WMIC ( 9 | ID INT IDENTITY PRIMARY KEY, 10 | CmdOutput VARCHAR(1000) 11 | ) 12 | 13 | INSERT INTO #WMIC (CmdOutput) 14 | EXECUTE master..xp_cmdshell 'WMIC.exe Volume get Label, BlockSize, Name /FORMAT:RAWXML' 15 | 16 | DECLARE @Cmd VARCHAR(MAX) = '' 17 | DECLARE @Xml XML 18 | 19 | SELECT @Cmd = @Cmd + COALESCE(w.CmdOutput, '') 20 | FROM #WMIC w 21 | ORDER BY w.ID 22 | 23 | SET @Xml = CAST(@Cmd AS XML) 24 | 25 | SELECT 26 | Label = Process.value('(PROPERTY[@NAME="Label"]/VALUE)[1]', 'VARCHAR(100)'), 27 | BlockSize = Process.value('(PROPERTY[@NAME="BlockSize"]/VALUE)[1]', 'INT'), 28 | Name = Process.value('(PROPERTY[@NAME="Name"]/VALUE)[1]', 'VARCHAR(100)') 29 | FROM @Xml.nodes('/COMMAND/RESULTS/CIM/INSTANCE') AS WmiTbl(Process) 30 | --Exclude the "system reserved" volume/disk. 31 | WHERE 32 | COALESCE(Process.value('(PROPERTY[@NAME="Label"]/VALUE)[1]', 'VARCHAR(100)'), '') <> 33 | 'System Reserved' 34 | --My database files are not on C:\ -- exclude this volume/disk. 35 | --AND Process.value('(PROPERTY[@NAME="Name"]/VALUE)[1]', 'VARCHAR(100)') <> 'C:\' 36 | --Volumes with NULL block size? Are these DVD/CD rom drives? Exclude these. 37 | AND Process.value('(PROPERTY[@NAME="BlockSize"]/VALUE)[1]', 'INT') IS NOT NULL 38 | 39 | DROP TABLE #WMIC 40 | 41 | --Disable xp_cmdshell 42 | EXEC sp_configure 'show advanced options', 1 43 | RECONFIGURE 44 | EXEC sp_configure 'xp_cmdshell', 0 45 | RECONFIGURE 46 | GO -------------------------------------------------------------------------------- /Find Buffer Descriptors what's in SQL Server buffer.sql: -------------------------------------------------------------------------------- 1 | --DMV to view the buffer descriptors 2 | SELECT so.name,* 3 | FROM sys.dm_os_buffer_descriptors AS obd 4 | INNER JOIN sys.allocation_units AS au 5 | ON obd.allocation_unit_id = au.allocation_unit_id 6 | INNER JOIN sys.partitions AS part 7 | ON au.container_id = part.hobt_id 8 | INNER JOIN sys.objects AS so 9 | ON part.object_id = so.object_id 10 | WHERE obd.database_id = DB_ID() 11 | AND so.is_ms_shipped = 0 12 | 13 | -------------------------------------------------------------------------------- /Find Buffer Pool Cache Size For Each Db.sql: -------------------------------------------------------------------------------- 1 | -- Get total buffer usage by database for current instance 2 | SELECT DB_NAME(database_id) AS [Database Name], 3 | COUNT(*) * 8/1024.0 AS [Cached Size (MB)] 4 | FROM sys.dm_os_buffer_descriptors 5 | WHERE database_id > 4 -- system databases 6 | AND database_id <> 32767 -- ResourceDB 7 | GROUP BY DB_NAME(database_id) 8 | ORDER BY [Cached Size (MB)] DESC; 9 | 10 | -- Tells you how much memory (in the buffer pool) is being used by each database -------------------------------------------------------------------------------- /Find Buffer Usage For Each Database.sql: -------------------------------------------------------------------------------- 1 | ;WITH src AS 2 | ( 3 | SELECT 4 | [Object] = o.name, 5 | [Type] = o.type_desc, 6 | [Index] = COALESCE(i.name, ''), 7 | [Index_Type] = i.type_desc, 8 | p.[object_id], 9 | p.index_id, 10 | au.allocation_unit_id 11 | FROM 12 | sys.partitions AS p 13 | INNER JOIN 14 | sys.allocation_units AS au 15 | ON p.hobt_id = au.container_id 16 | INNER JOIN 17 | sys.objects AS o 18 | ON p.[object_id] = o.[object_id] 19 | INNER JOIN 20 | sys.indexes AS i 21 | ON o.[object_id] = i.[object_id] 22 | AND p.index_id = i.index_id 23 | WHERE 24 | au.[type] IN (1,2,3) 25 | AND o.is_ms_shipped = 0 26 | ) 27 | SELECT 28 | src.[Object], 29 | src.[Type], 30 | src.[Index], 31 | src.Index_Type, 32 | buffer_pages = COUNT_BIG(b.page_id), 33 | buffer_mb = COUNT_BIG(b.page_id) / 128 34 | FROM 35 | src 36 | INNER JOIN 37 | sys.dm_os_buffer_descriptors AS b 38 | ON src.allocation_unit_id = b.allocation_unit_id 39 | WHERE 40 | b.database_id = DB_ID() 41 | GROUP BY 42 | src.[Object], 43 | src.[Type], 44 | src.[Index], 45 | src.Index_Type 46 | ORDER BY 47 | buffer_pages DESC; -------------------------------------------------------------------------------- /Find CPU Intensive Queries.sql: -------------------------------------------------------------------------------- 1 | --https://www.simple-talk.com/blogs/2016/02/16/how-to-find-cpu-intensive-queries/ 2 | --check the most cpu intensive queries in our system: 3 | --comment out the database name to get the queries for all the databases 4 | SELECT 5 | -- using statement_start_offset and 6 | -- statement_end_offset we get the query text 7 | -- from inside the entire batch 8 | SUBSTRING(qt.TEXT, (qs.statement_start_offset/2)+1, 9 | ((CASE qs.statement_end_offset 10 | WHEN -1 THEN DATALENGTH(qt.TEXT) 11 | ELSE qs.statement_end_offset 12 | END 13 | - qs.statement_start_offset)/2)+1) 14 | as [Text], 15 | qt.dbid, 16 | db_name(qt.dbid) AS 'DatabaseName', 17 | qs.execution_count, 18 | qs.total_logical_reads, qs.last_logical_reads, 19 | qs.total_logical_writes, qs.last_logical_writes, 20 | qs.total_worker_time, 21 | qs.last_worker_time, 22 | -- converting microseconds to seconds 23 | qs.total_elapsed_time/1000000 total_elapsed_time_in_S, 24 | qs.last_elapsed_time/1000000 last_elapsed_time_in_S, 25 | qs.last_execution_time, 26 | qp.query_plan 27 | FROM sys.dm_exec_query_stats qs 28 | -- Retrieve the query text 29 | CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) qt 30 | -- Retrieve the query plan 31 | CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) qp 32 | --WHERE db_name(qt.dbid) = 'Advatar' 33 | ORDER BY qs.total_worker_time DESC -- CPU time -------------------------------------------------------------------------------- /Find Cached Plans and SQL.sql: -------------------------------------------------------------------------------- 1 | --DBCC FREEPROCCACHE 2 | --GO 3 | 4 | --SELECT * FROM AdventureWorks.Production.Product 5 | --GO 6 | 7 | --SELECT * FROM AdventureWorks.Production.Product -- return records 8 | --GO 9 | 10 | SELECT stats.execution_count AS exec_count, 11 | p.size_in_bytes as [size], 12 | [sql].[text] as [plan_text] 13 | FROM sys.dm_exec_cached_plans p 14 | outer apply sys.dm_exec_sql_text (p.plan_handle) sql 15 | join sys.dm_exec_query_stats stats 16 | ON stats.plan_handle = p.plan_handle 17 | GO 18 | -------------------------------------------------------------------------------- /Find Cached Temporary Object Count.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | DOMCC.[type], 3 | DOMCC.pages_kb, 4 | DOMCC.pages_in_use_kb, 5 | DOMCC.entries_count, 6 | DOMCC.entries_in_use_count 7 | FROM sys.dm_os_memory_cache_counters AS DOMCC 8 | WHERE 9 | DOMCC.[name] = N'Temporary Tables & Table Variables'; -------------------------------------------------------------------------------- /Find Column Exist in Multiple Tables.sql: -------------------------------------------------------------------------------- 1 | --Find Column Name that exists in multiple tables 2 | select c.table_name 3 | , c.column_name 4 | from information_schema.columns as c 5 | inner join information_schema.tables as t 6 | on t.table_name = c.table_name 7 | where c.column_name = 'applicationid' 8 | and t.table_type = 'base table' 9 | order by c.table_name 10 | 11 | -------------------------------------------------------------------------------- /Find Column Names and Data Types.sql: -------------------------------------------------------------------------------- 1 | -- Find Column Names and Data Types for all columns in all tables 2 | SELECT Object_Name(C.Object_Id) AS TableName, 3 | C.Column_Id, 4 | C.Name, 5 | T.Name, 6 | C.Max_Length, 7 | C.Precision, 8 | C.Scale, 9 | C.Is_Nullable 10 | FROM sys.Columns AS C (NOLOCK) 11 | INNER JOIN sys.Types AS T (NOLOCK) 12 | ON C.System_Type_Id = T.System_Type_Id 13 | WHERE C.Object_id > 100 14 | ORDER BY Object_Name(C.Object_Id) -------------------------------------------------------------------------------- /Find Columns With Constraints And Defaults.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/himadanreddy/SQL-DBA-SCRIPTS/3111841fe0efca6d018929c71d2201506912ddcb/Find Columns With Constraints And Defaults.sql -------------------------------------------------------------------------------- /Find Compressed Indexes For The Object.sql: -------------------------------------------------------------------------------- 1 | SELECT OBJECT_NAME(i.object_id), i.name, i.index_id, i.type_desc, p.partition_number, p.rows, p.data_compression_desc, i.is_unique, i.is_primary_key, i.has_filter,i.filter_definition 2 | FROM sys.indexes AS i 3 | INNER JOIN sys.partitions AS p ON p.object_id = i.object_id AND p.index_id = i.index_id 4 | WHERE i.object_id = OBJECT_ID('ods.SGDW_FactItems') 5 | ORDER BY i.index_id 6 | -------------------------------------------------------------------------------- /Find Compressed Indexes.sql: -------------------------------------------------------------------------------- 1 | -- Find compressed indexes in SQL 2008 and above 2 | SELECT 3 | SCHEMA_NAME(ST.schema_id) AS 'SchemaName' 4 | , st.name AS 'TableName' 5 | , si.name AS 'IndexName' 6 | , si.index_id 7 | , si.type_desc AS 'IndexType' 8 | , sp.data_compression 9 | , sp.data_compression_desc 10 | FROM sys.partitions AS SP 11 | INNER JOIN sys.tables AS ST ON st.object_id = sp.object_id 12 | INNER JOIN sys.indexes AS SI ON si.object_id = st.object_id 13 | WHERE data_compression <> 0 14 | ORDER BY ST.name, SI.index_id; 15 | -------------------------------------------------------------------------------- /Find Compressed Objects in SQL 2008.sql: -------------------------------------------------------------------------------- 1 | -- Find Compressed objects in SQL 2008 2 | SELECT st.name, 3 | st.object_id, 4 | sp.partition_id, 5 | sp.partition_number, 6 | sp.data_compression, 7 | sp.data_compression_desc 8 | FROM sys.partitions SP 9 | INNER JOIN sys.tables ST 10 | ON st.object_id = sp.object_id 11 | WHERE data_compression <> 0 -------------------------------------------------------------------------------- /Find Compression Info For All Indexes In A Database.sql: -------------------------------------------------------------------------------- 1 | -- Find Compression Info for all indexes in a Database 2 | SELECT 3 | SCHEMA_NAME(st.schema_id) AS SchemaName, 4 | st.name AS TableName, 5 | CASE WHEN SI.index_id = 0 THEN 'HEAP' 6 | ELSE si.name 7 | END AS IndexName, 8 | si.index_id, 9 | sp.partition_number, 10 | sp.data_compression, 11 | sp.data_compression_desc 12 | FROM sys.partitions AS SP 13 | INNER JOIN sys.tables AS ST ON st.object_id = sp.object_id 14 | INNER JOIN sys.indexes AS si ON si.object_id = ST.object_id AND si.index_id = SP.index_id 15 | ORDER BY SchemaName, TableName 16 | OPTION(RECOMPILE); 17 | -------------------------------------------------------------------------------- /Find Connection Info to SQL Server.sql: -------------------------------------------------------------------------------- 1 | -- Get a count of SQL connections by IP address 2 | SELECT ec.client_net_address, es.[program_name], 3 | es.[host_name], es.login_name, 4 | COUNT(ec.session_id) AS [connection count] 5 | FROM sys.dm_exec_sessions AS es 6 | INNER JOIN sys.dm_exec_connections AS ec 7 | ON es.session_id = ec.session_id 8 | GROUP BY ec.client_net_address, es.[program_name], es.[host_name], es.login_name 9 | ORDER BY ec.client_net_address, es.[program_name]; 10 | 11 | -- Get a count of SQL connections by login_name 12 | SELECT login_name, COUNT(session_id) AS [session_count] 13 | FROM sys.dm_exec_sessions 14 | GROUP BY login_name 15 | ORDER BY login_name; -------------------------------------------------------------------------------- /Find Count of Connections To SQL Server.sql: -------------------------------------------------------------------------------- 1 | -- Get a count of SQL connections by IP address (Connection Counts by IP Address) 2 | SELECT ec.client_net_address, es.[program_name], es.[host_name], es.login_name, 3 | COUNT(ec.session_id) AS [connection count] 4 | FROM sys.dm_exec_sessions AS es WITH (NOLOCK) 5 | INNER JOIN sys.dm_exec_connections AS ec WITH (NOLOCK) 6 | ON es.session_id = ec.session_id 7 | GROUP BY ec.client_net_address, es.[program_name], es.[host_name], es.login_name 8 | ORDER BY ec.client_net_address, es.[program_name] OPTION (RECOMPILE); 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /Find Data Size And Log Size And Percent Log Used For All DBs.sql: -------------------------------------------------------------------------------- 1 | SELECT instance_name AS 'Database Name', 2 | MAX(CASE 3 | WHEN counter_name = 'Data File(s) Size (KB)' 4 | THEN cntr_value 5 | ELSE 0 6 | END) AS 'Data File(s) Size (KB)', 7 | MAX(CASE 8 | WHEN counter_name = 'Log File(s) Size (KB)' 9 | THEN cntr_value 10 | ELSE 0 11 | END) AS 'Log File(s) Size (KB)', 12 | MAX(CASE 13 | WHEN counter_name = 'Log File(s) Used Size (KB)' 14 | THEN cntr_value 15 | ELSE 0 16 | END) AS 'Log File(s) Used Size (KB)', 17 | MAX(CASE 18 | WHEN counter_name = 'Percent Log Used' 19 | THEN cntr_value 20 | ELSE 0 21 | END) AS 'Percent Log Used' 22 | --FROM sysperfinfo -- SQL Server 2000 system table deprecated 23 | FROM sys.dm_os_performance_counters 24 | WHERE counter_name IN 25 | ( 26 | 'Data File(s) Size (KB)', 27 | 'Log File(s) Size (KB)', 28 | 'Log File(s) Used Size (KB)', 29 | 'Percent Log Used' 30 | ) 31 | AND instance_name != '_total' 32 | GROUP BY instance_name -------------------------------------------------------------------------------- /Find Database Backup Size In GB.sql: -------------------------------------------------------------------------------- 1 | -- If database name changed or database dropped the query most like will not return any info for that database 2 | USE master; 3 | GO 4 | SELECT 5 | CAST(b.backup_start_date AS DATE) AS 'BackupDate' 6 | , b.database_name AS 'DatabaseName' 7 | , CAST(b.backup_size/1024000 AS DECIMAL (19,2)) AS 'SizeInMegaByte' 8 | , CAST(b.backup_size/1024000000 AS DECIMAL (19,2)) AS 'SizeInGigaByte' 9 | FROM msdb.dbo.backupset AS b 10 | INNER JOIN sys.databases AS d ON b.database_name = d.name 11 | WHERE b.Type = 'D' 12 | AND d.database_id > 4 13 | AND b.backup_start_date > '20170617' 14 | ORDER BY b.database_name, b.backup_start_date DESC -------------------------------------------------------------------------------- /Find Database File Growth Settings.sql: -------------------------------------------------------------------------------- 1 | SELECT 'Database Name' = DB_NAME(database_id) 2 | ,'FileName' = NAME 3 | ,FILE_ID 4 | ,'size' = CONVERT(NVARCHAR(15), CONVERT(BIGINT, size) * 8) + N' KB' 5 | ,'maxsize' = ( 6 | CASE max_size 7 | WHEN - 1 8 | THEN N'Unlimited' 9 | ELSE CONVERT(NVARCHAR(15), CONVERT(BIGINT, max_size) * 8) + N' KB' 10 | END 11 | ) 12 | ,'growth' = ( 13 | CASE is_percent_growth 14 | WHEN 1 15 | THEN CONVERT(NVARCHAR(15), growth) + N'%' 16 | ELSE CONVERT(NVARCHAR(15), CONVERT(BIGINT, growth) * 8) + N' KB' 17 | END 18 | ) 19 | ,'type_desc' = type_desc 20 | FROM sys.master_files 21 | ORDER BY database_id -------------------------------------------------------------------------------- /Find Database File space and File Group Info.sql: -------------------------------------------------------------------------------- 1 | -- Find the available space in each file and file group data 2 | SELECT dbf.File_id AS FileId, 3 | dbf.Name AS DBFileName, 4 | dbf.physical_name AS PhysicalDBFileName, 5 | dbf.Type_Desc AS FileType, 6 | STR((dbf.Size/128.0),10,2) AS TotalSpace, 7 | --CAST(FILEPROPERTY(name, 'SpaceUsed')/128.0 AS INT) AS SpaceUsed, 8 | CAST(FILEPROPERTY(dbf.name, 'SpaceUsed')/128.0 AS DECIMAL(9,2)) AS SpaceUsed, 9 | STR((Size/128.0 - CAST(FILEPROPERTY(dbf.name, 'SpaceUsed') AS int)/128.0),9,2) AS FreeSpaceInMB, 10 | dbfg.Name AS DBFileGroupName, 11 | dbfg.type_desc AS DataFGDesc, 12 | dbfg.is_default AS ISDefaultFileGroup 13 | FROM sys.database_files AS dbf 14 | LEFT OUTER JOIN sys.data_spaces AS dbfg 15 | ON dbf.data_space_id = dbfg.data_space_id 16 | ORDER BY dbf.type_desc DESC, dbf.file_id 17 | OPTION(RECOMPILE); 18 | 19 | -- configured size for Tempdb 20 | SELECT 21 | name, file_id, type_desc, size * 8 / 1024 [TempdbSizeInMB] 22 | FROM sys.master_files 23 | WHERE DB_NAME(database_id) = 'tempdb' 24 | ORDER BY type_desc DESC, file_id 25 | OPTION(RECOMPILE); 26 | -------------------------------------------------------------------------------- /Find Database Mail Profile and Account Info.sql: -------------------------------------------------------------------------------- 1 | USE msdb; 2 | GO 3 | SELECT p.profile_id, a.account_id, a.email_address, a. display_name,s.servertype, s.servername, s.port, s.username, s.credential_id 4 | , a.name, p.[description] as 'ProfileDesc' ,a.[description] as 'AccountDesc' 5 | FROM dbo.sysmail_profileaccount as pa 6 | INNER JOIN dbo.sysmail_account as a on pa.account_id = a.account_id 7 | INNER JOIN dbo.sysmail_profile as p on p.profile_id = pa.profile_id 8 | INNER JOIN dbo.sysmail_server as s on s.account_id = a.account_id -------------------------------------------------------------------------------- /Find Database Role Permissions2.sql: -------------------------------------------------------------------------------- 1 | SELECT DISTINCT rp.name, 2 | ObjectType = rp.type_desc, 3 | PermissionType = pm.class_desc, 4 | pm.permission_name, 5 | pm.state_desc, 6 | ObjectType = CASE 7 | WHEN obj.type_desc IS NULL 8 | OR obj.type_desc = 'SYSTEM_TABLE' THEN 9 | pm.class_desc 10 | ELSE obj.type_desc 11 | END, 12 | s.Name as SchemaName, 13 | [ObjectName] = Isnull(ss.name, Object_name(pm.major_id)) 14 | FROM sys.database_principals rp 15 | INNER JOIN sys.database_permissions pm 16 | ON pm.grantee_principal_id = rp.principal_id 17 | LEFT JOIN sys.schemas ss 18 | ON pm.major_id = ss.schema_id 19 | LEFT JOIN sys.objects obj 20 | ON pm.[major_id] = obj.[object_id] 21 | LEFT JOIN sys.schemas s 22 | ON s.schema_id = obj.schema_id 23 | WHERE rp.type_desc = 'DATABASE_ROLE' 24 | --AND pm.class_desc <> 'DATABASE' 25 | AND RP.name = 'BI_GROUP' 26 | ORDER BY rp.name, 27 | rp.type_desc, 28 | pm.class_desc -------------------------------------------------------------------------------- /Find Database Size for All Databases.sql: -------------------------------------------------------------------------------- 1 | USE master; 2 | GO 3 | SELECT 4 | @@SERVERNAME AS 'ServerName' 5 | , d.name AS 'DatabaseName' 6 | , CAST(SUM(mf.size) AS bigint) * 8 / 1024 AS 'DatabaseSizeMB' 7 | , CAST(CAST((CAST(SUM(mf.size) AS bigint) * 8 / 1024) AS numeric(10,2)) / 1024 AS NUMERIC(10,2)) AS 'DatabaseSizeGB' 8 | FROM sys.master_files AS mf 9 | INNER JOIN sys.databases AS d ON d.database_id = mf.database_id 10 | WHERE d.database_id > 4 -- Skip system databases 11 | GROUP BY d.name 12 | ORDER BY DatabaseSizeGB DESC; 13 | -------------------------------------------------------------------------------- /Find Date of the Sunday Week Day.sql: -------------------------------------------------------------------------------- 1 | 2 | -- Find the date of the Week day 3 | SELECT CONVERT(VARCHAR(10), DATEADD(D, -1 * DATEPART(WEEKDAY, GETDATE()), GETDATE()) + 1, 101) AS SundayWeekDay, 4 | CONVERT(VARCHAR(10), CASE WHEN DATEPART(WEEKDAY, GETDATE()) = 2 THEN GETDATE() ELSE GETDATE()-DATEPART(WEEKDAY, GETDATE()-2) END, 101) AS MondayWeekDay -------------------------------------------------------------------------------- /Find Degree of Selectivity.sql: -------------------------------------------------------------------------------- 1 | --Finds the Degree of Selectivity for a Specific Column in a Row 2 | Declare @total_unique float 3 | Declare @total_rows float 4 | Declare @selectivity_ratio float 5 | 6 | SELECT @total_unique = 0 7 | SELECT @total_rows = 0 8 | SELECT @selectivity_ratio = 0 9 | 10 | --Finds the Total Number of Unique Rows in a Table 11 | --Be sure to replace OrderID below with the name of your column 12 | --Be sure to replace [Order Details] below with your table name 13 | SELECT @total_unique = (SELECT COUNT(DISTINCT OrderID) FROM [Order Details]) 14 | 15 | --Calculates Total Number of Rows in Table 16 | --Be sure to replace [Order Details] below with your table name 17 | SELECT @total_rows = (SELECT COUNT(*) FROM [Order Details]) 18 | 19 | --Calculates Selectivity Ratio for a Specific Column 20 | SELECT @selectivity_ratio = ROUND((SELECT @total_unique/@total_rows),2,2) 21 | SELECT @selectivity_ratio as 'Selectivity Ratio' -------------------------------------------------------------------------------- /Find Deprecated Features Being Used.sql: -------------------------------------------------------------------------------- 1 | select instance_name as [Deprecated Feature] 2 | ,cntr_value as [Frequency Used] 3 | from sys.dm_os_performance_counters 4 | where object_name = 'SQLServer:Deprecated Features' 5 | --object_name = 'MSSQL$ODS:Deprecated Features' -- CHANGE THE INSTANCE NAME 6 | and cntr_value > 0 7 | order by cntr_value desc 8 | -------------------------------------------------------------------------------- /Find Detailed Information on Unused Indexes.sql: -------------------------------------------------------------------------------- 1 | -- Find Unused Index Script 2 | SELECT 3 | DB_NAME() AS 'DatbaseName' 4 | , s.Name AS 'SchemaName' 5 | , o.name AS 'TableName' 6 | , i.name AS 'IndexName' 7 | , i.index_id AS 'IndexID' 8 | , dm_ius.user_seeks AS 'UserSeek' 9 | , dm_ius.user_scans AS 'UserScans' 10 | , dm_ius.user_lookups AS 'UserLookups' 11 | , dm_ius.user_updates AS 'UserUpdates' 12 | , p.TableRows AS 'RowCount' 13 | , 'DROP INDEX ' + QUOTENAME(i.name) 14 | +' ON ' + QUOTENAME(s.name) + '.' + QUOTENAME(OBJECT_NAME(dm_ius.OBJECT_ID)) AS 'DropStatement' 15 | FROM sys.dm_db_index_usage_stats dm_ius 16 | INNER JOIN sys.indexes i 17 | ON i.index_id = dm_ius.index_id AND dm_ius.OBJECT_ID = i.OBJECT_ID 18 | INNER JOIN sys.objects o 19 | ON dm_ius.OBJECT_ID = o.OBJECT_ID 20 | INNER JOIN sys.schemas s 21 | ON o.schema_id = s.schema_id 22 | INNER JOIN (SELECT SUM(p.rows) TableRows, p.index_id, p.OBJECT_ID 23 | FROM sys.partitions p 24 | GROUP BY p.index_id, p.OBJECT_ID) p 25 | ON p.index_id = dm_ius.index_id 26 | AND dm_ius.OBJECT_ID = p.OBJECT_ID 27 | WHERE OBJECTPROPERTY(dm_ius.OBJECT_ID,'IsUserTable') = 1 28 | AND dm_ius.database_id = DB_ID() 29 | AND i.type_desc = 'nonclustered' 30 | AND i.is_primary_key = 0 31 | AND i.is_unique_constraint = 0 32 | AND o.is_ms_shipped = 0 33 | ORDER BY (dm_ius.user_seeks + dm_ius.user_scans + dm_ius.user_lookups) ASC 34 | OPTION (RECOMPILE); 35 | 36 | -------------------------------------------------------------------------------- /Find Estimated Compression and Compress Table.sql: -------------------------------------------------------------------------------- 1 | EXEC sp_estimate_data_compression_savings 'dbo', 'ClickRateCMSShared', NULL, NULL, 'PAGE' ; 2 | GO 3 | 4 | EXEC sp_estimate_data_compression_savings 'dbo', 'ClickRateCMSShared', NULL, NULL, 'ROW' ; 5 | GO 6 | 7 | 8 | /****** 9 | 10 | EXEC sp_spaceused 'dbo.ClickRate_Dashboard' 11 | go 12 | --Warning: Option sort_in_tempdb is not applicable to table ClickRate_Dashboard because it does not have a clustered index. This option will be applied only to the table's nonclustered indexes, if it has any. 13 | ALTER TABLE dbo.ClickRate_Dashboard REBUILD PARTITION = ALL 14 | WITH 15 | (DATA_COMPRESSION = PAGE, 16 | SORT_IN_TEMPDB = ON 17 | ) 18 | GO 19 | 20 | EXEC sp_spaceused 'dbo.ClickRateCMSShared' 21 | go 22 | 23 | 24 | name rows reserved data index_size unused 25 | ClickRateCMSShared 26274 3920 KB 3848 KB 48 KB 24 KB 26 | ClickRateCMSShared 26274 2384 KB 2352 KB 24 KB 8 KB 27 | 28 | *****/ -------------------------------------------------------------------------------- /Find Estimated Cost Of Execution Plan.sql: -------------------------------------------------------------------------------- 1 | -- Place to start Cost Threshold For Parallellism 2 | ;WITH XMLNAMESPACES ( 3 | DEFAULT N'http://schemas.microsoft.com/sqlserver/2004/07/showplan' 4 | ) 5 | , TextPlans 6 | AS (SELECT CAST(detqp.query_plan AS XML) AS QueryPlan, 7 | detqp.dbid 8 | FROM sys.dm_exec_query_stats AS deqs 9 | CROSS APPLY sys.dm_exec_text_query_plan( 10 | deqs.plan_handle, 11 | deqs.statement_start_offset, 12 | deqs.statement_end_offset 13 | ) AS detqp 14 | ), 15 | QueryPlans 16 | AS (SELECT RelOp.pln.value(N'@EstimatedTotalSubtreeCost', N'float') AS EstimatedCost, 17 | RelOp.pln.value(N'@NodeId', N'integer') AS NodeId, 18 | tp.dbid, 19 | tp.QueryPlan 20 | FROM TextPlans AS tp 21 | CROSS APPLY tp.queryplan.nodes(N'//RelOp')RelOp(pln) 22 | ) 23 | SELECT qp.EstimatedCost, db_name(qp.dbid) as 'DBName', qp.QueryPlan 24 | FROM QueryPlans AS qp 25 | WHERE qp.NodeId = 0; 26 | -------------------------------------------------------------------------------- /Find Execution Plan And Plan Handle with Usage Count.sql: -------------------------------------------------------------------------------- 1 | SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; 2 | WITH XMLNAMESPACES 3 | (DEFAULT 'http://schemas.microsoft.com/sqlserver/2004/07/showplan') 4 | SELECT 5 | COALESCE(DB_NAME(p.dbid), p.query_plan.value('(//RelOp/OutputList/ColumnReference/@Database)[1]','nvarchar(128)')) AS DatabaseName --Works in a number of cases, but not perfect. 6 | ,DB_NAME(p.dbid) + '.' + OBJECT_SCHEMA_NAME(p.objectid, p.dbid) + '.' + OBJECT_NAME(p.objectid, p.dbid) AS ObjectName 7 | ,cp.objtype 8 | ,p.query_plan 9 | ,cp.UseCounts 10 | ,cp.plan_handle 11 | ,CAST('' AS xml) AS SQLText 12 | FROM sys.dm_exec_cached_plans cp 13 | CROSS APPLY sys.dm_exec_query_plan(cp.plan_handle) p 14 | CROSS APPLY sys.dm_exec_sql_text(cp.plan_handle) as q 15 | WHERE cp.cacheobjtype = 'Compiled Plan' 16 | --AND p.query_plan.exist('//RelOp[@Parallel = "1"]') = 1 17 | AND P.dbid = DB_ID() 18 | AND P.objectid = OBJECT_ID('dbo.fn_Merchant_CommissionsDefaultAndVariable_Select_By_MerchantIDListReferSourceAndPlatformType') 19 | ORDER BY COALESCE(DB_NAME(p.dbid), p.query_plan.value('(//RelOp/OutputList/ColumnReference/@Database)[1]','nvarchar(128)')), UseCounts DESC 20 | OPTION (RECOMPILE); 21 | -------------------------------------------------------------------------------- /Find Execution Plan Cache Usage For Stored Procs.sql: -------------------------------------------------------------------------------- 1 | SELECT p.name AS [SP Name], qs.execution_count, 2 | ISNULL(qs.execution_count/DATEDIFF(Minute, qs.cached_time, GETDATE()), 0) AS [Calls/Minute], 3 | qs.total_worker_time/qs.execution_count AS [AvgWorkerTime], qs.total_worker_time AS [TotalWorkerTime], 4 | qs.total_elapsed_time, qs.total_elapsed_time/qs.execution_count AS [avg_elapsed_time], 5 | qs.cached_time 6 | FROM sys.procedures AS p WITH (NOLOCK) 7 | INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK) 8 | ON p.[object_id] = qs.[object_id] 9 | WHERE qs.database_id = DB_ID() 10 | AND DATEDIFF(Minute, qs.cached_time, GETDATE()) > 0 11 | order by qs.cached_time asc 12 | OPTION (RECOMPILE); -------------------------------------------------------------------------------- /Find Execution Plan Cache Usage.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/himadanreddy/SQL-DBA-SCRIPTS/3111841fe0efca6d018929c71d2201506912ddcb/Find Execution Plan Cache Usage.sql -------------------------------------------------------------------------------- /Find Execution Plan For Cached Object.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | deqs.query_hash 3 | , deqs.query_plan_hash 4 | , deqs.creation_time 5 | , deqs.execution_count 6 | , deqs.last_execution_time 7 | , deqs.max_logical_reads 8 | , deqp.query_plan 9 | , dest.text 10 | FROM sys.dm_exec_query_stats AS deqs 11 | CROSS APPLY sys.dm_exec_query_plan(deqs.plan_handle) AS deqp 12 | CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest 13 | WHERE deqp.objectid = OBJECT_ID('dbo.fn_Merchant_CommissionsDefaultAndVariable_Select_By_MerchantIDPlatformType') 14 | OPTION (RECOMPILE); -------------------------------------------------------------------------------- /Find Execution Plan for Cached Queries.sql: -------------------------------------------------------------------------------- 1 | 2 | SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; 3 | 4 | WITH XMLNAMESPACES 5 | (DEFAULT 'http://schemas.microsoft.com/sqlserver/2004/07/showplan') 6 | SELECT 7 | COALESCE(DB_NAME(p.dbid), p.query_plan.value('(//RelOp/OutputList/ColumnReference/@Database)[1]','nvarchar(128)')) AS DatabaseName --Works in a number of cases, but not perfect. 8 | ,DB_NAME(p.dbid) + '.' + OBJECT_SCHEMA_NAME(p.objectid, p.dbid) + '.' + OBJECT_NAME(p.objectid, p.dbid) AS ObjectName 9 | ,cp.objtype 10 | ,p.query_plan 11 | ,cp.UseCounts 12 | ,cp.plan_handle 13 | ,CAST('' AS xml) AS SQLText 14 | FROM sys.dm_exec_cached_plans cp 15 | CROSS APPLY sys.dm_exec_query_plan(cp.plan_handle) p 16 | CROSS APPLY sys.dm_exec_sql_text(cp.plan_handle) as q 17 | WHERE cp.cacheobjtype = 'Compiled Plan' 18 | AND p.query_plan.exist('//RelOp[@Parallel = "1"]') = 1 19 | ORDER BY COALESCE(DB_NAME(p.dbid), p.query_plan.value('(//RelOp/OutputList/ColumnReference/@Database)[1]','nvarchar(128)')), UseCounts DESC 20 | -------------------------------------------------------------------------------- /Find Execution Plan for Parallel Executed Cached Queries.sql: -------------------------------------------------------------------------------- 1 | 2 | SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; 3 | 4 | WITH XMLNAMESPACES 5 | (DEFAULT 'http://schemas.microsoft.com/sqlserver/2004/07/showplan') 6 | SELECT 7 | COALESCE(DB_NAME(p.dbid), p.query_plan.value('(//RelOp/OutputList/ColumnReference/@Database)[1]','nvarchar(128)')) AS DatabaseName --Works in a number of cases, but not perfect. 8 | ,DB_NAME(p.dbid) + '.' + OBJECT_SCHEMA_NAME(p.objectid, p.dbid) + '.' + OBJECT_NAME(p.objectid, p.dbid) AS ObjectName 9 | ,cp.objtype 10 | ,p.query_plan 11 | ,cp.UseCounts 12 | ,cp.plan_handle 13 | ,CAST('' AS xml) AS SQLText 14 | FROM sys.dm_exec_cached_plans cp 15 | CROSS APPLY sys.dm_exec_query_plan(cp.plan_handle) p 16 | CROSS APPLY sys.dm_exec_sql_text(cp.plan_handle) as q 17 | WHERE cp.cacheobjtype = 'Compiled Plan' 18 | AND p.query_plan.exist('//RelOp[@Parallel = "1"]') = 1 19 | ORDER BY COALESCE(DB_NAME(p.dbid), p.query_plan.value('(//RelOp/OutputList/ColumnReference/@Database)[1]','nvarchar(128)')), UseCounts DESC 20 | -------------------------------------------------------------------------------- /Find Execution Plans Using Specific Index.sql: -------------------------------------------------------------------------------- 1 | 2 | SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED 3 | GO 4 | 5 | DECLARE @IndexName sysname = 'ncIndx1'; 6 | SET @IndexName = QUOTENAME(@IndexName,'['); 7 | 8 | WITH XMLNAMESPACES(DEFAULT 'http://schemas.microsoft.com/sqlserver/2004/07/showplan') 9 | ,IndexSearch 10 | AS ( 11 | SELECT qp.query_plan 12 | ,cp.usecounts 13 | ,ix.query('.') AS StmtSimple 14 | FROM sys.dm_exec_cached_plans cp 15 | OUTER APPLY sys.dm_exec_query_plan(cp.plan_handle) qp 16 | CROSS APPLY qp.query_plan.nodes('//StmtSimple') AS p(ix) 17 | WHERE query_plan.exist('//Object[@Index = sql:variable("@IndexName")]') = 1 18 | ) 19 | SELECT StmtSimple.value('StmtSimple[1]/@StatementText', 'VARCHAR(4000)') AS sql_text 20 | ,obj.value('@Database','sysname') AS database_name 21 | ,obj.value('@Schema','sysname') AS schema_name 22 | ,obj.value('@Table','sysname') AS table_name 23 | ,obj.value('@Index','sysname') AS index_name 24 | ,ixs.query_plan 25 | FROM IndexSearch ixs 26 | CROSS APPLY StmtSimple.nodes('//Object') AS o(obj) 27 | WHERE obj.exist('//Object[@Index = sql:variable("@IndexName")]') = 1 28 | -------------------------------------------------------------------------------- /Find FK Constraints.sql: -------------------------------------------------------------------------------- 1 | 2 | SELECT OBJECT_NAME(parent_object_id) AS ParentTableName, 3 | OBJECT_NAME(referenced_object_id) AS ChildTableName, 4 | Name AS FKName, 5 | Type_Desc, 6 | Create_Date 7 | FROM sys.foreign_keys 8 | ORDER BY ParentTableName -------------------------------------------------------------------------------- /Find File Size and Available Space for Database.sql: -------------------------------------------------------------------------------- 1 | -- Find the available space in each database file and file group data 2 | SELECT dbf.File_id AS FileId, 3 | dbf.Name AS DBFileName, 4 | dbf.physical_name AS PhysicalDBFileName, 5 | dbf.Type_Desc AS FileType, 6 | STR((dbf.Size/128.0),10,2) AS TotalSpace, 7 | --CAST(FILEPROPERTY(name, 'SpaceUsed')/128.0 AS INT) AS SpaceUsed, 8 | CAST(FILEPROPERTY(dbf.name, 'SpaceUsed')/128.0 AS DECIMAL(9,2)) AS SpaceUsed, 9 | STR((Size/128.0 - CAST(FILEPROPERTY(dbf.name, 'SpaceUsed') AS int)/128.0),9,2) AS FreeSpaceInMB, 10 | dbfg.Name AS DBFileGroupName, 11 | dbfg.type_desc AS DataFGDesc, 12 | dbfg.is_default AS ISDefaultFileGroup 13 | FROM sys.database_files AS dbf 14 | LEFT OUTER JOIN sys.data_spaces AS dbfg 15 | ON dbf.data_space_id = dbfg.data_space_id 16 | ORDER BY dbf.type_desc DESC, dbf.file_id -------------------------------------------------------------------------------- /Find First and Last Day of The month.sql: -------------------------------------------------------------------------------- 1 | 2 | 3 | DECLARE @mydate DATETIME 4 | SELECT @mydate = GETDATE() 5 | SELECT CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(@mydate)),@mydate),101) , 6 | 'Last Day of Previous Month' 7 | UNION 8 | SELECT CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(@mydate)-1),@mydate),101) AS Date_Value, 9 | 'First Day of Current Month' AS Date_Type 10 | UNION 11 | 12 | SELECT CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(DATEADD(mm,1,@mydate))),DATEADD(mm,1,@mydate)),101) , 13 | 'Last Day of Current Month' 14 | UNION 15 | SELECT CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(DATEADD(mm,1,@mydate))-1),DATEADD(mm,1,@mydate)),101) , 16 | 'First Day of Next Month' -------------------------------------------------------------------------------- /Find Free Space in DB Files.sql: -------------------------------------------------------------------------------- 1 | 2 | -- Find the available space in each file 3 | SELECT File_id AS FileId, 4 | Name, 5 | Type_Desc AS FileType, 6 | STR((Size/128.0),10,2) AS TotalSpace, 7 | --CAST(FILEPROPERTY(name, 'SpaceUsed')/128.0 AS INT) AS SpaceUsed, 8 | CAST(FILEPROPERTY(name, 'SpaceUsed')/128.0 AS DECIMAL(9,2)) AS SpaceUsed, 9 | STR((Size/128.0 - CAST(FILEPROPERTY(name, 'SpaceUsed') AS int)/128.0),9,2) AS FreeSpaceInMB 10 | FROM sys.database_files 11 | ORDER BY NAME -------------------------------------------------------------------------------- /Find Full Text Indexes in a Database.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | t.name AS TableName, 3 | c.name AS FTCatalogName , 4 | i.name AS UniqueIdxName, 5 | cl.name AS ColumnName 6 | FROM 7 | sys.tables t 8 | INNER JOIN 9 | sys.fulltext_indexes fi 10 | ON 11 | t.[object_id] = fi.[object_id] 12 | INNER JOIN 13 | sys.fulltext_index_columns ic 14 | ON 15 | ic.[object_id] = t.[object_id] 16 | INNER JOIN 17 | sys.columns cl 18 | ON 19 | ic.column_id = cl.column_id 20 | AND ic.[object_id] = cl.[object_id] 21 | INNER JOIN 22 | sys.fulltext_catalogs c 23 | ON 24 | fi.fulltext_catalog_id = c.fulltext_catalog_id 25 | INNER JOIN 26 | sys.indexes i 27 | ON 28 | fi.unique_index_id = i.index_id 29 | AND fi.[object_id] = i.[object_id]; -------------------------------------------------------------------------------- /Find General Info for All Databases.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/himadanreddy/SQL-DBA-SCRIPTS/3111841fe0efca6d018929c71d2201506912ddcb/Find General Info for All Databases.sql -------------------------------------------------------------------------------- /Find Heap Tables.sql: -------------------------------------------------------------------------------- 1 | -- FIND TABLE WITHOUT CLUSTERED INDEX (HEAPS) 2 | SELECT OBJECT_SCHEMA_NAME(i.object_id) AS SchemaName, 3 | o.name AS TableName, 4 | p.rows AS RecordCount, 5 | o.is_published AS Published, 6 | i.type_desc AS TableTypeDesc, 7 | o.type_desc AS SystemOrUserTable, 8 | o.create_date AS CreateDate 9 | FROM sys.indexes AS i 10 | INNER JOIN sys.objects AS o 11 | ON i.object_id = o.object_id 12 | INNER JOIN sys.partitions AS P 13 | ON p.object_id = o.object_id 14 | WHERE o.type_desc = 'USER_TABLE' 15 | AND i.type_desc = 'HEAP' 16 | AND o.is_ms_shipped = 0 -- Return only user created objects 17 | AND p.index_id = 0 18 | ORDER BY OBJECT_SCHEMA_NAME(i.object_id),o.name 19 | GO -------------------------------------------------------------------------------- /Find ID Gap In A Table.sql: -------------------------------------------------------------------------------- 1 | ;WITH 2 | cte AS ( 3 | SELECT 4 | [StatementDeliveryConfigurationID], 5 | RowNum = ROW_NUMBER() OVER (ORDER BY [StatementDeliveryConfigurationID]) 6 | FROM [Fin].[StatementDeliveryConfigurations]), 7 | cte2 AS ( 8 | SELECT *, DENSE_RANK() OVER (ORDER BY [StatementDeliveryConfigurationID] - RowNum) As Series 9 | FROM cte), 10 | cte3 AS ( 11 | SELECT *, COUNT(*) OVER (PARTITION BY Series) AS SCount 12 | FROM cte2), 13 | cte4 AS ( 14 | SELECT 15 | MinStatementDeliveryConfigurationID = MIN([StatementDeliveryConfigurationID]), 16 | MaxStatementDeliveryConfigurationID = MAX([StatementDeliveryConfigurationID]), 17 | Series 18 | FROM cte3 19 | GROUP BY Series) 20 | 21 | SELECT GapStart = a.MaxStatementDeliveryConfigurationID, GapEnd = b.MinStatementDeliveryConfigurationID 22 | , b.MinStatementDeliveryConfigurationID - a.MaxStatementDeliveryConfigurationID AS GapRange 23 | FROM cte4 a 24 | INNER JOIN cte4 b 25 | ON a.Series+1 = b.Series 26 | ORDER BY GapStart DESC; -------------------------------------------------------------------------------- /Find Index Column info.sql: -------------------------------------------------------------------------------- 1 | SELECT OBJECT_NAME(i.[object_id]) TableName , 2 | i.[name] IndexName , 3 | c.[name] ColumnName , 4 | ic.is_included_column , 5 | i.index_id , 6 | i.type_desc , 7 | i.is_unique , 8 | i.data_space_id , 9 | i.ignore_dup_key , 10 | i.is_primary_key , 11 | i.is_unique_constraint 12 | FROM sys.indexes i 13 | JOIN sys.index_columns ic 14 | ON ic.object_id = i.object_id 15 | AND i.index_id = ic.index_id 16 | JOIN sys.columns c 17 | ON ic.object_id = c.object_id 18 | AND ic.column_id = c.column_id 19 | --WHERE I.NAME = 'INDEX NAME' 20 | ORDER BY tableName , 21 | ic.index_id , 22 | ic.index_column_id -------------------------------------------------------------------------------- /Find Index Leaf Page Insert Update Delete Count.sql: -------------------------------------------------------------------------------- 1 | -- Find Index Insert, Update, Delete Count 2 | SELECT 3 | OBJECT_SCHEMA_NAME(A.[OBJECT_ID]) AS 'SchemaName' 4 | , OBJECT_NAME(A.[OBJECT_ID]) AS [OBJECT NAME], 5 | I.[NAME] AS [INDEX NAME], 6 | A.LEAF_INSERT_COUNT, 7 | A.LEAF_UPDATE_COUNT, 8 | A.LEAF_DELETE_COUNT 9 | FROM SYS.DM_DB_INDEX_OPERATIONAL_STATS (NULL,NULL,NULL,NULL ) A 10 | INNER JOIN SYS.INDEXES AS I 11 | ON I.[OBJECT_ID] = A.[OBJECT_ID] 12 | AND I.INDEX_ID = A.INDEX_ID 13 | WHERE OBJECTPROPERTY(A.[OBJECT_ID],'IsUserTable') = 1 14 | --AND OBJECT_NAME(A.[OBJECT_ID]) = 'BILLABLELEADS' 15 | ORDER BY 16 | A.LEAF_INSERT_COUNT DESC, 17 | A.LEAF_UPDATE_COUNT DESC, 18 | A.LEAF_DELETE_COUNT DESC -------------------------------------------------------------------------------- /Find Index Size and Stats For All Indexes.sql: -------------------------------------------------------------------------------- 1 | -- Index size 2 | select 3 | object_schema_name(o.object_id) AS 'SchemaName', 4 | o.Name AS 'TableName', 5 | i.Name AS 'IndexName', 6 | max(s.row_count) AS 'RowCount', 7 | sum(s.reserved_page_count) * 8.0 / (1024) as 'MB', 8 | (8 * 1024* sum(s.reserved_page_count)) / max(s.row_count) as 'Bytes/Row', 9 | s.reserved_page_count, 10 | p.Data_compression_desc 11 | , STATS_DATE(i.[object_id], i.index_id) AS StatisticsDate 12 | from 13 | sys.dm_db_partition_stats s, 14 | sys.indexes i, 15 | sys.objects o, 16 | sys.partitions as p 17 | where 18 | s.object_id = i.object_id 19 | and s.index_id = i.index_id 20 | --and s.index_id >0 21 | and i.object_id = o.object_id 22 | and p.object_id = o.object_id 23 | and p.index_id = i.Index_id 24 | and o.is_ms_shipped = 0 -- Non Microsoft Objects 25 | --and o.Name = 'FactInventory' 26 | group by i.Name, o.Name, p.Data_compression_desc,o.object_id, i.index_id, STATS_DATE(i.[object_id], i.index_id),s.reserved_page_count 27 | having SUM(s.row_count) > 0 28 | order by SchemaName, tablename, i.index_id-- MB desc 29 | OPTION(RECOMPILE); 30 | -------------------------------------------------------------------------------- /Find Index Stats Date For All Tables.sql: -------------------------------------------------------------------------------- 1 | -- Find the Index Stats Date for All Table 2 | SELECT 3 | OBJECT_SCHEMA_NAME(t.object_id) AS SchemaName 4 | , t.name AS TableName 5 | , i.name AS IndexName 6 | , i.index_id 7 | , i.type_desc AS IndexType 8 | , STATS_DATE(i.[object_id], i.index_id) AS StatisticsDate 9 | FROM sys.indexes AS i 10 | INNER JOIN sys.tables as t ON i.[object_id] = t.[object_id] 11 | WHERE t.type = 'U' --Only get indexes for User Created Tables 12 | AND i.name IS NOT NULL 13 | ORDER BY OBJECT_SCHEMA_NAME(t.object_id), t.name, i.type 14 | OPTION(RECOMPILE) 15 | -------------------------------------------------------------------------------- /Find Index Stats Date For Single Table.sql: -------------------------------------------------------------------------------- 1 | 2 | -- Find the Index Stats Date for Single Table 3 | SELECT o.name AS TableName 4 | , i.name AS IndexName 5 | , i.type_desc AS IndexType 6 | , STATS_DATE(i.[object_id], i.index_id) AS StatisticsDate 7 | 8 | FROM sys.indexes i 9 | INNER JOIN sys.objects o 10 | ON i.[object_id] = o.[object_id] 11 | 12 | WHERE o.type = 'U' --Only get indexes for User Created Tables 13 | AND i.name IS NOT NULL 14 | AND o.name = 'AccountActivities' -- Change The Name Of The Table 15 | ORDER BY o.name, i.type 16 | -------------------------------------------------------------------------------- /Find Index Usage Statistics.sql: -------------------------------------------------------------------------------- 1 | select db_name(database_id), 2 | object_name(object_id), 3 | * 4 | from 5 | sys.dm_db_index_usage_stats 6 | where user_seeks = 0 7 | and user_scans = 0 8 | and db_name(database_id) = 'netquoteqa' 9 | order by 10 | user_updates desc 11 | -------------------------------------------------------------------------------- /Find Index Usage and Recommended Missing Indexes.sql: -------------------------------------------------------------------------------- 1 | -- Find index usage 2 | SELECT OBJECT_NAME(S.[OBJECT_ID]) AS [OBJECT NAME], 3 | I.[NAME] AS [INDEX NAME], 4 | USER_SEEKS, 5 | USER_SCANS, 6 | USER_LOOKUPS, 7 | USER_UPDATES 8 | FROM SYS.DM_DB_INDEX_USAGE_STATS AS S 9 | INNER JOIN SYS.INDEXES AS I 10 | ON I.[OBJECT_ID] = S.[OBJECT_ID] 11 | AND I.INDEX_ID = S.INDEX_ID 12 | WHERE OBJECTPROPERTY(S.[OBJECT_ID],'IsUserTable') = 1 13 | --AND OBJECT_NAME(S.[OBJECT_ID]) = 'AccountPaymentInformation'-- CHANGE THE TABLE NAME 14 | 15 | -- Find Recommended missing indexes 16 | select d.* 17 | , s.avg_total_user_cost 18 | , s.avg_user_impact 19 | , s.last_user_seek 20 | ,s.unique_compiles 21 | from sys.dm_db_missing_index_group_stats s 22 | ,sys.dm_db_missing_index_groups g 23 | ,sys.dm_db_missing_index_details d 24 | where s.group_handle = g.index_group_handle 25 | and d.index_handle = g.index_handle 26 | and database_id = db_id() 27 | --and (d.object_id = 171147655 or d.object_id = 107147427) -- CHANGE OBJECT IDS 28 | order by D.[STATEMENT],s.avg_user_impact desc 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /Find Index dept and Page Count for Each Level of index.sql: -------------------------------------------------------------------------------- 1 | 2 | --Find Index depth and page count for each index 3 | SELECT OBJECT_NAME(P.OBJECT_ID) AS 'Table' 4 | , I.name AS 'Index' 5 | , P.index_id AS 'IndexID' 6 | , P.index_type_desc 7 | , P.index_depth 8 | , P.page_count 9 | FROM sys.dm_db_index_physical_stats (DB_ID(), 10 | OBJECT_ID('Sales.SalesOrderDetail'), 11 | NULL, NULL, NULL) P 12 | JOIN sys.indexes I ON I.OBJECT_ID = P.OBJECT_ID 13 | AND I.index_id = P.index_id; 14 | 15 | 16 | -- Find Page Count for Each node in the index (leaf, intermidate, root) 17 | SELECT OBJECT_NAME(P.OBJECT_ID) AS 'Table' 18 | , I.name AS 'Index' 19 | , P.index_id AS 'IndexID' 20 | , P.index_type_desc 21 | , P.index_level 22 | , P.page_count 23 | FROM sys.dm_db_index_physical_stats (DB_ID(), OBJECT_ID('Sales.SalesOrderDetail'), 2, NULL, 'DETAILED') P 24 | JOIN sys.indexes I ON I.OBJECT_ID = P.OBJECT_ID 25 | AND I.index_id = P.index_id; 26 | -------------------------------------------------------------------------------- /Find SQL Server Agent Job Steps Execution Information.sql: -------------------------------------------------------------------------------- 1 | -- Find SQL Server Agent Job Steps Execution Information 2 | SELECT 3 | [sJOB].[job_id] AS [JobID] 4 | , [sJOB].[name] AS [JobName] 5 | , [sJSTP].[step_uid] AS [StepID] 6 | , [sJSTP].[step_id] AS [StepNo] 7 | , [sJSTP].[step_name] AS [StepName] 8 | , CASE [sJSTP].[last_run_outcome] 9 | WHEN 0 THEN 'Failed' 10 | WHEN 1 THEN 'Succeeded' 11 | WHEN 2 THEN 'Retry' 12 | WHEN 3 THEN 'Canceled' 13 | WHEN 5 THEN 'Unknown' 14 | END AS [LastRunStatus] 15 | , STUFF( 16 | STUFF(RIGHT('000000' + CAST([sJSTP].[last_run_duration] AS VARCHAR(6)), 6) 17 | , 3, 0, ':') 18 | , 6, 0, ':') 19 | AS [LastRunDuration (HH:MM:SS)] 20 | , [sJSTP].[last_run_retries] AS [LastRunRetryAttempts] 21 | , CASE [sJSTP].[last_run_date] 22 | WHEN 0 THEN NULL 23 | ELSE 24 | CAST( 25 | CAST([sJSTP].[last_run_date] AS CHAR(8)) 26 | + ' ' 27 | + STUFF( 28 | STUFF(RIGHT('000000' + CAST([sJSTP].[last_run_time] AS VARCHAR(6)), 6) 29 | , 3, 0, ':') 30 | , 6, 0, ':') 31 | AS DATETIME) 32 | END AS [LastRunDateTime] 33 | FROM 34 | [msdb].[dbo].[sysjobsteps] AS [sJSTP] 35 | INNER JOIN [msdb].[dbo].[sysjobs] AS [sJOB] 36 | ON [sJSTP].[job_id] = [sJOB].[job_id] 37 | ORDER BY [JobName], [StepNo] -------------------------------------------------------------------------------- /Find all DMVs.sql: -------------------------------------------------------------------------------- 1 | 2 | SELECT 'sys.' + name AS DmvName 3 | FROM sys.system_objects 4 | WHERE name LIKE 'dm%'; 5 | GO 6 | -------------------------------------------------------------------------------- /Find execution plan handle and remove it from plan cache.sql: -------------------------------------------------------------------------------- 1 | SELECT cp.plan_handle, st.[text] 2 | FROM sys.dm_exec_cached_plans AS cp 3 | CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS st 4 | WHERE [text] LIKE N'%fn_Merchant_CommissionsDefaultAndVariable_Select_By_MerchantIDsPlatformType%' 5 | OPTION (RECOMPILE); 6 | 7 | -- Remove the specific plan from the cache using the plan handle 8 | /*** 9 | 10 | DBCC FREEPROCCACHE (0x05001500ADD91769505FF30EC000000001000000000000000000000000000000000000000000000000000000) 11 | 12 | ***/ 13 | -------------------------------------------------------------------------------- /Find if column has Default.sql: -------------------------------------------------------------------------------- 1 | -- find if column has default value set 2 | SELECT DC.* 3 | FROM SYS.COLUMNS AS C (NOLOCK) 4 | INNER JOIN SYS.DEFAULT_CONSTRAINTS AS DC (NOLOCK) 5 | ON C.OBJECT_ID = DC.PARENT_OBJECT_ID 6 | AND C.COLUMN_ID = DC.PARENT_COLUMN_ID 7 | WHERE OBJECT_NAME(C.OBJECT_ID) = 'LEADS' -- REPLACE TABLE NAME 8 | AND C.Name = 'LeadManagementLeadTime' -- REPLACE COLUMN NAME 9 | AND Type_Desc = 'DEFAULT_CONSTRAINT' 10 | 11 | -------------------------------------------------------------------------------- /FindLogFileSizeChangeDates.sql: -------------------------------------------------------------------------------- 1 | USE DBA; 2 | GO 3 | SELECT TM.DatabaseName, TM.LogSizeMB, MIN(TM.LogDate) AS SizeMinDate, MAX(TM.LogDate) AS SizeMaxDate 4 | FROM DBO.TransLogMonitor AS TM 5 | INNER JOIN ( 6 | SELECT DISTINCT DatabaseName, LogSizeMB 7 | FROM DBO.TransLogMonitor WITH (NOLOCK) 8 | WHERE DatabaseName = 'EbgProd' ) AS TM2 ON TM.DatabaseName = TM2.DatabaseName AND TM.LogSizeMB = TM2.LogSizeMB 9 | GROUP BY TM.DatabaseName, TM.LogSizeMB -------------------------------------------------------------------------------- /GetAvgTaskCountsTotal_Chap03_RunnableTaskCount.sql: -------------------------------------------------------------------------------- 1 | SELECT AVG(current_tasks_count) AS [Avg Current Task], 2 | 3 | AVG(runnable_tasks_count) AS [Avg Wait Task] 4 | 5 | FROM sys.dm_os_schedulers 6 | 7 | WHERE scheduler_id < 255 8 | 9 | AND status = 'VISIBLE ONLINE' -------------------------------------------------------------------------------- /GetBufferHitCacheRatio_Ch05_sys.dm_os_performance_countersHowtoReadCalculate .sql: -------------------------------------------------------------------------------- 1 | SELECT (a.cntr_value * 1.0 / b.cntr_value) * 100 [BufferCacheHitRatio] 2 | 3 | FROM (SELECT * FROM sys.dm_os_performance_counters 4 | 5 | WHERE counter_name = 'Buffer cache hit ratio' 6 | 7 | AND object_name = CASE WHEN @@SERVICENAME = 'MSSQLSERVER' 8 | 9 | THEN 'SQLServer:Buffer Manager' 10 | 11 | ELSE 'MSSQL$' + rtrim(@@SERVICENAME) + 12 | 13 | ':Buffer Manager' END ) a 14 | 15 | CROSS JOIN 16 | 17 | (SELECT * from sys.dm_os_performance_counters 18 | 19 | WHERE counter_name = 'Buffer cache hit ratio base' 20 | 21 | and object_name = CASE WHEN @@SERVICENAME = 'MSSQLSERVER' 22 | 23 | THEN 'SQLServer:Buffer Manager' 24 | 25 | ELSE 'MSSQL$' + rtrim(@@SERVICENAME) + 26 | 27 | ':Buffer Manager' END ) b; -------------------------------------------------------------------------------- /GetFillFactorForAllIndexesOnDatabase_Chap04_FillFactor.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | 3 | db_name() AS DbName 4 | 5 | , B.name AS TableName 6 | 7 | , C.name AS IndexName 8 | 9 | , C.fill_factor AS IndexFillFactor 10 | 11 | , D.rows AS RowsCount 12 | 13 | , A.avg_fragmentation_in_percent 14 | 15 | , A.page_count 16 | 17 | , GetDate() as [TimeStamp] 18 | 19 | FROM sys.dm_db_index_physical_stats(DB_ID(),NULL,NULL,NULL,NULL) A 20 | 21 | INNER JOIN sys.objects B 22 | 23 | ON A.object_id = B.object_id 24 | 25 | INNER JOIN sys.indexes C 26 | 27 | ON B.object_id = C.object_id AND A.index_id = C.index_id 28 | 29 | INNER JOIN sys.partitions D 30 | 31 | ON B.object_id = D.object_id AND A.index_id = D.index_id 32 | 33 | WHERE C.index_id > 0 34 | 35 | -------------------------------------------------------------------------------- /GetHistoricalCPUUtilizationSQLvsOtherProcesses_Chap03_CPUBlameGame.sql: -------------------------------------------------------------------------------- 1 | set nocount on 2 | 3 | declare @ts_now bigint 4 | 5 | select @ts_now = cpu_ticks /( cpu_ticks / ms_ticks ) 6 | 7 | from sys.dm_os_sys_info 8 | 9 | select /*top 1*/ record_id,dateadd(ms, -1 * (@ts_now - [timestamp]), GetDate()) as EventTime, 10 | 11 | SQLProcessUtilization,SystemIdle,100 - SystemIdle - SQLProcessUtilization as OtherProcessUtilization 12 | 13 | from (select record.value('(./Record/@id)[1]', 'int') as record_id, 14 | 15 | record.value('(./Record/SchedulerMonitorEvent/SystemHealth/SystemIdle)[1]', 'int') as SystemIdle, 16 | 17 | record.value('(./Record/SchedulerMonitorEvent/SystemHealth/ProcessUtilization)[1]', 'int') as SQLProcessUtilization, 18 | 19 | timestamp from (select timestamp, convert(xml, record) as record 20 | 21 | from sys.dm_os_ring_buffers 22 | 23 | where ring_buffer_type = N'RING_BUFFER_SCHEDULER_MONITOR' and record like '%%') as x 24 | 25 | ) as y order by record_id desc -------------------------------------------------------------------------------- /GetIODiskLatencyPercentageByIOStallsByDatabase_Chap03_IOMayBeWhyYourServerIsSlow.sql: -------------------------------------------------------------------------------- 1 | WITH DBIO AS 2 | 3 | ( 4 | 5 | SELECT 6 | 7 | DB_NAME(IVFS.database_id) AS db, 8 | 9 | CASE WHEN MF.type = 1 THEN 'log' ELSE 'data' END AS file_type, 10 | 11 | SUM(IVFS.num_of_bytes_read + IVFS.num_of_bytes_written) AS io, 12 | 13 | SUM(IVFS.io_stall) AS io_stall 14 | 15 | FROM sys.dm_io_virtual_file_stats(NULL, NULL) AS IVFS 16 | 17 | JOIN sys.master_files AS MF 18 | 19 | ON IVFS.database_id = MF.database_id 20 | 21 | AND IVFS.file_id = MF.file_id 22 | 23 | GROUP BY DB_NAME(IVFS.database_id), MF.type 24 | 25 | ) 26 | 27 | SELECT db, file_type, 28 | 29 | CAST(1. * io / (1024 * 1024) AS DECIMAL(12, 2)) AS io_mb, 30 | 31 | CAST(io_stall / 1000. AS DECIMAL(12, 2)) AS io_stall_s, 32 | 33 | CAST(100. * io_stall / SUM(io_stall) OVER() 34 | 35 | AS DECIMAL(10, 2)) AS io_stall_pct 36 | 37 | FROM DBIO 38 | 39 | ORDER BY io_stall DESC; -------------------------------------------------------------------------------- /GetIODiskUsagePercentageByDatabase_Chap03_IOMayBeWhyYourServerIsSlow.sql: -------------------------------------------------------------------------------- 1 | WITH Cu_IO_Stats 2 | 3 | AS 4 | 5 | ( 6 | 7 | SELECT 8 | 9 | DB_NAME(database_id) AS database_name, 10 | 11 | CAST(SUM(num_of_bytes_read + num_of_bytes_written) / 1048576. 12 | 13 | AS DECIMAL(12, 2)) AS io_in_mb 14 | 15 | FROM sys.dm_io_virtual_file_stats(NULL, NULL) AS DM_IO_Stats 16 | 17 | GROUP BY database_id 18 | 19 | ) 20 | 21 | SELECT 22 | 23 | ROW_NUMBER() OVER(ORDER BY io_in_mb DESC) AS row_num, 24 | 25 | database_name, 26 | 27 | io_in_mb, 28 | 29 | CAST(io_in_mb / SUM(io_in_mb) OVER() * 100 30 | 31 | AS DECIMAL(5, 2)) AS pct 32 | 33 | FROM Cu_IO_Stats 34 | 35 | ORDER BY row_num; -------------------------------------------------------------------------------- /GetIODiskUsagePercentageByDriveLetter_Chap03_IOMayBeWhyYourServerIsSlow.sql: -------------------------------------------------------------------------------- 1 | With IOdrv as 2 | 3 | (select db_name(mf.database_id) as database_name, mf.physical_name, 4 | 5 | left(mf.physical_name, 1) as drive_letter, 6 | 7 | vfs.num_of_writes, 8 | 9 | vfs.num_of_bytes_written as bytes_written, 10 | 11 | vfs.io_stall_write_ms, 12 | 13 | mf.type_desc, vfs.num_of_reads, vfs.num_of_bytes_read, vfs.io_stall_read_ms, 14 | 15 | vfs.io_stall, vfs.size_on_disk_bytes 16 | 17 | from sys.master_files mf 18 | 19 | join sys.dm_io_virtual_file_stats(NULL, NULL) vfs 20 | 21 | on mf.database_id=vfs.database_id and mf.file_id=vfs.file_id 22 | 23 | --order by vfs.num_of_bytes_written desc) 24 | 25 | ) 26 | 27 | select database_name,drive_letter, bytes_written, 28 | 29 | Percentage = RTRIM(CONVERT(DECIMAL(5,2), 30 | 31 | bytes_written*100.0/(SELECT SUM(bytes_written) FROM IOdrv))) 32 | 33 | --where drive_letter='D' <-- You can put specify drive ))) 34 | 35 | + '%' 36 | 37 | from IOdrv --where drive_letter='D' 38 | 39 | order by bytes_written desc -------------------------------------------------------------------------------- /GetIdealMemUsagePercentTotalAndTargetMemory_Chap03_FindAllCurrentlyBlockedRequests.sql: -------------------------------------------------------------------------------- 1 | /* Get all blocked processes 2 | SELECT * FROM sys.sysprocesses WHERE blocked > 0 3 | 4 | DBCC INPUTBUFFER (SPID) -- Replace (SPID) with blocked spid from above query for text) */ 5 | 6 | SELECT sqltext.TEXT, 7 | 8 | xr.session_id, 9 | 10 | xr.status, 11 | 12 | xr.blocking_session_id, 13 | 14 | xr.command, 15 | 16 | xr.cpu_time, 17 | 18 | xr.total_elapsed_time, 19 | 20 | xr.wait_resource 21 | 22 | FROM sys.dm_exec_requests xr 23 | 24 | CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS sqltext 25 | 26 | WHERE status='suspended' -------------------------------------------------------------------------------- /GetIdealMemUsagePercentTotalAndTargetMemory_Chap03_MemoryPressure.sql: -------------------------------------------------------------------------------- 1 | SELECT ROUND(100.0 * ( SELECT CAST([cntr_value] AS FLOAT) 2 | 3 | FROM sys.dm_os_performance_counters 4 | 5 | WHERE [object_name] LIKE '%Memory Manager%' 6 | 7 | AND [counter_name] = 'Total Server Memory (KB)' ) / ( SELECT CAST([cntr_value] AS FLOAT) 8 | 9 | FROM sys.dm_os_performance_counters 10 | 11 | WHERE [object_name] LIKE '%Memory Manager%' 12 | 13 | AND [counter_name] = 'Target Server Memory (KB)') , 2)AS [IDEAL MEMORY USAGE] -------------------------------------------------------------------------------- /GetIndexUsageSimple_Chap04_CommonIndexIssues_IndexUsage.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | 3 | DB_NAME(database_id) As DBName, 4 | 5 | Object_Name(object_id,database_id) As ObjectName, 6 | 7 | database_id, 8 | 9 | object_id, 10 | 11 | Index_id, 12 | 13 | user_seeks, 14 | 15 | user_scans, 16 | 17 | user_lookups, 18 | 19 | user_updates, 20 | 21 | last_user_seek, 22 | 23 | last_user_scan, 24 | 25 | last_user_lookup, 26 | 27 | last_user_update 28 | 29 | FROM sys.dm_db_index_usage_stats 30 | 31 | order by DB_NAME(database_id) 32 | 33 | GO -------------------------------------------------------------------------------- /GetMissingIdxCreate_Chap04_MissingIndexes.sql: -------------------------------------------------------------------------------- 1 | -- GetMissingIdxCreate script - Missing indexes with CREATE statement 2 | 3 | SELECT MID.[statement] AS ObjectName 4 | 5 | ,MID.equality_columns AS EqualityColumns 6 | 7 | ,MID.inequality_columns AS InequalityColms 8 | 9 | ,MID.included_columns AS IncludedColumns 10 | 11 | ,MIGS.user_seeks 12 | 13 | ,MIGS.last_user_seek AS LastUserSeek 14 | 15 | ,MIGS.avg_total_user_cost 16 | 17 | ,MIGS.avg_user_impact 18 | 19 | ,N'CREATE NONCLUSTERED INDEX ' + 20 | 21 | N'ON ' + MID.[statement] + 22 | 23 | N' (' + MID.equality_columns 24 | 25 | + ISNULL(', ' + MID.inequality_columns, N'') + 26 | 27 | N') ' + ISNULL(N'INCLUDE (' + MID.included_columns + N');', ';') 28 | 29 | AS CreateStatement 30 | 31 | FROM sys.dm_db_missing_index_group_stats AS MIGS 32 | 33 | INNER JOIN sys.dm_db_missing_index_groups AS MIG 34 | 35 | ON MIGS.group_handle = MIG.index_group_handle 36 | 37 | INNER JOIN sys.dm_db_missing_index_details AS MID 38 | 39 | ON MIG.index_handle = MID.index_handle 40 | 41 | WHERE database_id = DB_ID() 42 | 43 | AND MIGS.last_user_seek >= DATEDIFF(month, GetDate(), -1) 44 | 45 | ORDER BY MIGS.avg_user_impact DESC; -------------------------------------------------------------------------------- /GetPendingIORequests_Chap03_IOMayBeWhyYourServerIsSlow.sql: -------------------------------------------------------------------------------- 1 | select database_id, 2 | 3 | file_id, 4 | 5 | io_stall, 6 | 7 | io_pending_ms_ticks, 8 | 9 | scheduler_address 10 | 11 | from sys.dm_io_virtual_file_stats(NULL, NULL) iovfs, 12 | 13 | sys.dm_io_pending_io_requests as iopior 14 | 15 | where iovfs.file_handle = iopior.io_handle -------------------------------------------------------------------------------- /GetPendingMemoryGrantsWithQueries_Chap03_MemoryPressure.sql: -------------------------------------------------------------------------------- 1 | SELECT mg.granted_memory_kb, mg.session_id, t.text, qp.query_plan 2 | 3 | FROM sys.dm_exec_query_memory_grants AS mg 4 | 5 | CROSS APPLY sys.dm_exec_sql_text(mg.sql_handle) AS t 6 | 7 | CROSS APPLY sys.dm_exec_query_plan(mg.plan_handle) AS qp 8 | 9 | -- where mg.session_id <> @@SPID /*uncomment to exclude your current session*/ 10 | 11 | ORDER BY 1 DESC OPTION (MAXDOP 1) 12 | -------------------------------------------------------------------------------- /GetRawPerfCounterValuesTotalAndTargetMemory_Chap03_MemoryPressure.sql: -------------------------------------------------------------------------------- 1 | SELECT [counter_name], [cntr_value] 2 | 3 | FROM sys.dm_os_performance_counters 4 | 5 | WHERE [object_name] 6 | 7 | LIKE '%Memory Manager%' 8 | 9 | AND [counter_name] IN ('Total Server Memory (KB)', 'Target Server Memory (KB)') 10 | -------------------------------------------------------------------------------- /GetSQLServerEngineProperties_Inventories_Chap02.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/himadanreddy/SQL-DBA-SCRIPTS/3111841fe0efca6d018929c71d2201506912ddcb/GetSQLServerEngineProperties_Inventories_Chap02.sql -------------------------------------------------------------------------------- /GetSingletonLookupCount_Chap04_CommonIndexIssues_IndexUsage.sql: -------------------------------------------------------------------------------- 1 | SELECT OBJECT_SCHEMA_NAME(idxos.object_id) + '.' + OBJECT_NAME(idxos.object_id) as table_name 2 | 3 | ,idx.name as index_name 4 | 5 | ,idxos.range_scan_count 6 | 7 | ,idxos.singleton_lookup_count 8 | 9 | FROM sys.dm_db_index_operational_stats(DB_ID(),NULL,NULL,NULL) idxos 10 | 11 | INNER JOIN sys.indexes idx ON idx.object_id = idxos.object_id AND idx.index_id = idxos.index_id 12 | 13 | WHERE OBJECTPROPERTY(idxos.object_id,'IsUserTable') = 1 14 | 15 | ORDER BY idxos.range_scan_count DESC 16 | 17 | GO -------------------------------------------------------------------------------- /GetTop20TotalQueryResponseTimeForIndividualQueries_Chap03_SlowPerformance.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/himadanreddy/SQL-DBA-SCRIPTS/3111841fe0efca6d018929c71d2201506912ddcb/GetTop20TotalQueryResponseTimeForIndividualQueries_Chap03_SlowPerformance.sql -------------------------------------------------------------------------------- /GetTopSQLServerWaits_Chap03_ObservingWaitStatistics.sql: -------------------------------------------------------------------------------- 1 | WITH Waits AS 2 | 3 | (SELECT wait_type, wait_time_ms / 1000. AS wait_time_s, 4 | 5 | 100. * wait_time_ms / SUM(wait_time_ms) OVER() AS pct, 6 | 7 | ROW_NUMBER() OVER(ORDER BY wait_time_ms DESC) AS rn 8 | 9 | FROM sys.dm_os_wait_stats 10 | 11 | WHERE wait_type NOT IN 12 | 13 | ('CLR_SEMAPHORE','LAZYWRITER_SLEEP','RESOURCE_QUEUE','SLEEP_TASK' 14 | 15 | ,'SLEEP_SYSTEMTASK','SQLTRACE_BUFFER_FLUSH','WAITFOR', 'LOGMGR_QUEUE','CHECKPOINT_QUEUE' 16 | 17 | ,'REQUEST_FOR_DEADLOCK_SEARCH','XE_TIMER_EVENT','BROKER_TO_FLUSH','BROKER_TASK_STOP','CLR_MANUAL_EVENT' 18 | 19 | ,'CLR_AUTO_EVENT','DISPATCHER_QUEUE_SEMAPHORE', 'FT_IFTS_SCHEDULER_IDLE_WAIT' 20 | 21 | ,'XE_DISPATCHER_WAIT', 'XE_DISPATCHER_JOIN', 'SQLTRACE_INCREMENTAL_FLUSH_SLEEP')) 22 | 23 | SELECT W1.wait_type, 24 | 25 | CAST(W1.wait_time_s AS DECIMAL(12, 2)) AS wait_time_s, 26 | 27 | CAST(W1.pct AS DECIMAL(12, 2)) AS pct, 28 | 29 | CAST(SUM(W2.pct) AS DECIMAL(12, 2)) AS running_pct 30 | 31 | FROM Waits AS W1 INNER JOIN Waits AS W2 ON W2.rn <= W1.rn 32 | 33 | GROUP BY W1.rn, W1.wait_type, W1.wait_time_s, W1.pct 34 | 35 | HAVING SUM(W2.pct) - W1.pct < 99 OPTION (RECOMPILE) -- percentage threshold -------------------------------------------------------------------------------- /GetTotalServerQueryResponseTime_Chap03_SlowPerformance.sql: -------------------------------------------------------------------------------- 1 | SELECT avg(total_elapsed_time / execution_count)/1000 As avg_query_response_time /*total_avg_elapsed_time (div by 1000 for ms, div by 1000000 for sec) */ 2 | FROM sys.dm_exec_query_stats -------------------------------------------------------------------------------- /GetTtlPlanCacheReUse_Chap03_AnatomyCPUMetadataQuery .sql: -------------------------------------------------------------------------------- 1 | select t1.cntr_value As [Batch Requests/sec], 2 | 3 | t2.cntr_value As [SQL Compilations/sec], 4 | 5 | plan_reuse_percentage = 6 | 7 | convert(decimal(15,2), 8 | 9 | (t1.cntr_value*1.0-t2.cntr_value*1.0)/t1.cntr_value*100) 10 | 11 | from 12 | 13 | master.sys.dm_os_performance_counters t1, 14 | 15 | master.sys.dm_os_performance_counters t2 16 | 17 | where 18 | 19 | t1.counter_name='Batch Requests/sec' and 20 | 21 | t2.counter_name='SQL Compilations/sec' -------------------------------------------------------------------------------- /GetWhatSQLServerIsWtgOnNow_Chap03_AnatomyCPUMetadataQuery.sql: -------------------------------------------------------------------------------- 1 | SELECT dm_ws.session_ID, 2 | 3 | dm_ws.wait_type, 4 | 5 | UPPER(dm_es.status) As status, 6 | 7 | dm_ws.wait_duration_ms, 8 | 9 | dm_t.TEXT, 10 | 11 | dm_es.cpu_time, 12 | 13 | dm_es.memory_usage, 14 | 15 | dm_es.logical_reads, 16 | 17 | dm_es.total_elapsed_time, 18 | 19 | dm_ws.blocking_session_id, 20 | 21 | dm_es.program_name, 22 | 23 | DB_NAME(dm_r.database_id) DatabaseName 24 | 25 | FROM sys.dm_os_waiting_tasks dm_ws 26 | 27 | INNER JOIN sys.dm_exec_requests dm_r ON dm_ws.session_id = dm_r.session_id 28 | 29 | INNER JOIN sys.dm_exec_sessions dm_es ON dm_es.session_id = dm_r.session_id 30 | 31 | CROSS APPLY sys.dm_exec_sql_text (dm_r.sql_handle) dm_t 32 | 33 | WHERE dm_es.is_user_process = 1 -------------------------------------------------------------------------------- /Get_sys.dm_os_performance_counters_DMV_Chap03_IntroWaits&Queues.sql: -------------------------------------------------------------------------------- 1 | SELECT object_name, 2 | 3 | counter_name, 4 | 5 | case when instance_name ='' 6 | 7 | then @@SERVICENAME end as instance_name, 8 | 9 | cntr_type, 10 | 11 | cntr_value 12 | 13 | FROM sys.dm_os_performance_counters -------------------------------------------------------------------------------- /IOstalls and PageIOLatch.sql: -------------------------------------------------------------------------------- 1 | select 2 | database_id, 3 | file_id, 4 | io_stall, 5 | io_pending_ms_ticks, 6 | scheduler_address 7 | from sys.dm_io_virtual_file_stats(NULL, NULL)t1, 8 | sys.dm_io_pending_io_requests as t2 9 | where t1.file_handle = t2.io_handle 10 | 11 | Select wait_type, 12 | waiting_tasks_count, 13 | wait_time_ms 14 | from sys.dm_os_wait_stats 15 | where wait_type like 'PAGEIOLATCH%' 16 | order by wait_type 17 | -------------------------------------------------------------------------------- /Identify Server Role Membership.sql: -------------------------------------------------------------------------------- 1 | 2 | SELECT SP_L.name AS Login_Name, SP_R.name AS Server_Role 3 | FROM master.sys.server_principals SP_L 4 | INNER JOIN master.sys.server_role_members SRM 5 | ON SP_L.principal_id = SRM.member_principal_id 6 | INNER JOIN master.sys.server_principals SP_R 7 | ON SRM.role_principal_id = SP_R.principal_id 8 | WHERE SP_R.type_desc = 'SERVER_ROLE' 9 | ORDER BY SP_R.name, SP_L.name; 10 | 11 | -------------------------------------------------------------------------------- /IdentifyQueriesCausingCPUPressure_Chap03_AnatomyCPUMetadataQuery .sql: -------------------------------------------------------------------------------- 1 | Select 2 | 3 | t.task_state, 4 | 5 | r.session_id, 6 | 7 | s.context_switches_count, 8 | 9 | s.pending_disk_io_count, 10 | 11 | s.scheduler_id AS CPU_ID, 12 | 13 | s.status AS Scheduler_Status, 14 | 15 | db_name(r.database_id) AS Database_Name, 16 | 17 | r.command, 18 | 19 | px.text 20 | 21 | from sys.dm_os_schedulers as s 22 | 23 | INNER JOIN sys.dm_os_tasks t on s.active_worker_address = t.worker_address 24 | 25 | INNER JOIN sys.dm_exec_requests r on t.task_address = r.task_address 26 | 27 | CROSS APPLY sys.dm_exec_sql_text(r.plan_handle) as px 28 | 29 | WHERE @@SPID<>r.session_id -- filters out this session 30 | 31 | -- AND t.task_state='RUNNABLE' --To filter out sessions that are waiting on CPU uncomment. -------------------------------------------------------------------------------- /Import Results to SQL Server.txt: -------------------------------------------------------------------------------- 1 | Importing the Results.TXT File into SQL Server 2 | 3 | In SQL Server Management Studio; 4 | 5 | Right-click on the database where you want to store the SQLIO performance data and click Tasks, Import Data. 6 | 7 | For Data Source, choose "Flat File Source". 8 | 9 | Browse to your results.txt file. 10 | 11 | Set the Format to Delimited, Text Qualifier to None, Header row delimiter to {CR}{LF}, and Header Rows to Skip to 0. 12 | 13 | Click on the Advanced tab on the left, and there should only be one column, Column 0. 14 | 15 | Set the DataType to text stream. 16 | 17 | Click Next. 18 | 19 | Your database server and storage database should be shown. Click Next. 20 | 21 | For the Destination Table, choose SQLIO_Import and click Edit Mappings. 22 | 23 | Set the Column 0 destination to be ResultText. Click OK, and click Next. 24 | 25 | Click Next until the wizard finishes and imports the data, and then close the wizard. -------------------------------------------------------------------------------- /Index_Usage_Stats_Ch07_DefiningCustomDataCollection.sql: -------------------------------------------------------------------------------- 1 | SELECT o.name Object_Name, 2 | SCHEMA_NAME(o.schema_id) Schema_name, 3 | i.name Index_name, 4 | i.Type_Desc, 5 | s.user_seeks, 6 | s.user_scans, 7 | s.user_lookups, 8 | s.user_updates, 9 | s.system_seeks, 10 | s.system_scans, 11 | s.system_lookups, 12 | getdate() Capture_Date 13 | FROM sys.objects AS o 14 | JOIN sys.indexes AS i 15 | ON o.object_id = i.object_id 16 | JOIN 17 | sys.dm_db_index_usage_stats AS s 18 | ON i.object_id = s.object_id 19 | AND i.index_id = s.index_id 20 | AND DB_ID() = s.database_id 21 | WHERE o.type = 'u' 22 | AND i.type IN (1, 2) 23 | AND(s.user_seeks > 0 OR s.user_scans > 0 OR s.user_lookups > 0 24 | OR s.system_seeks > 0 OR s.system_scans > 0 25 | OR s.system_lookups > 0) -------------------------------------------------------------------------------- /Investigate_Transaction.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | t1.resource_type, 3 | t1.resource_database_id, 4 | t1.resource_associated_entity_id, 5 | t1.request_mode, 6 | t1.request_session_id, 7 | t2.blocking_session_id 8 | FROM sys.dm_tran_locks as t1 9 | INNER JOIN sys.dm_os_waiting_tasks as t2 10 | ON t1.lock_owner_address = t2.resource_address; 11 | 12 | 13 | SELECT resource_type, resource_associated_entity_id, 14 | request_status, request_mode,request_session_id, 15 | resource_description 16 | FROM sys.dm_tran_locks 17 | WHERE resource_database_id = 5 18 | 19 | 20 | 21 | SELECT object_name(object_id), * 22 | FROM sys.partitions 23 | WHERE hobt_id=72057603711565824 24 | 25 | 26 | exec dbo.beta_lockinfo 27 | 28 | select status,* From sys.sysprocesses where blocked <> 0 29 | 30 | dbcc opentran 31 | 32 | --dbcc shrinkfile (2,7500) 33 | 34 | SELECT * FROM sys.dm_exec_sessions 35 | 36 | WHERE session_id = 81 37 | 38 | SELECT 39 | r.session_id, 40 | r.blocking_session_id, 41 | s.program_name, 42 | s.host_name, 43 | t.text 44 | 45 | FROM 46 | sys.dm_exec_requests r 47 | INNER JOIN sys.dm_exec_sessions s ON r.session_id = s.session_id 48 | CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) t 49 | 50 | WHERE 51 | s.is_user_process = 1 AND 52 | r.session_id = 81 53 | 54 | -------------------------------------------------------------------------------- /IsNumeric_BUG.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/himadanreddy/SQL-DBA-SCRIPTS/3111841fe0efca6d018929c71d2201506912ddcb/IsNumeric_BUG.sql -------------------------------------------------------------------------------- /JobDuration.sql: -------------------------------------------------------------------------------- 1 | WITH job_duration_view 2 | AS 3 | ( 4 | SELECT name, 5 | StartTime = CONVERT(DATETIME, RTRIM(last_run_date)) + 6 | (last_run_time * 9 + last_run_time % 10000 * 6 + last_run_time % 100 * 10 + 25 * last_run_duration) / 216e4 , 7 | CONVERT(CHAR(8),DATEADD(ss,last_run_duration,CAST(last_run_date AS CHAR(8))),114) 8 | AS duration 9 | FROM msdb.dbo.sysjobservers js 10 | JOIN msdb.dbo.sysjobs j ON j.job_id = js.job_id 11 | WHERE last_run_date >0 AND last_run_time >0 12 | ) SELECT name AS job_name,StartTime, 13 | StartTime -'19000101'+Duration AS EndDate ,Duration 14 | FROM job_duration_view 15 | order by name -------------------------------------------------------------------------------- /Job_duration.sql: -------------------------------------------------------------------------------- 1 | WITH job_duration_view 2 | AS 3 | ( 4 | SELECT name, 5 | StartTime = CONVERT(DATETIME, RTRIM(last_run_date)) + 6 | (last_run_time * 9 + last_run_time % 10000 * 6 + last_run_time % 100 * 10 + 25 * last_run_duration) / 216e4 , 7 | CONVERT(CHAR(8),DATEADD(ss,last_run_duration,CAST(last_run_date AS CHAR(8))),114) 8 | AS duration 9 | FROM msdb.dbo.sysjobservers js 10 | JOIN msdb.dbo.sysjobs j ON j.job_id = js.job_id 11 | WHERE last_run_date >0 AND last_run_time >0 12 | ) SELECT name AS job_name,StartTime, 13 | StartTime -'19000101'+Duration AS EndDate ,Duration 14 | FROM job_duration_view order by name -------------------------------------------------------------------------------- /Kill All the SPIDS to Single DB.sql: -------------------------------------------------------------------------------- 1 | -- Kill all spids to a single DB 2 | DECLARE @SQL VARCHAR(8000) 3 | 4 | SELECT @SQL=COALESCE(@SQL,'')+'Kill '+CAST(spid AS VARCHAR(10))+ '; ' 5 | FROM sys.sysprocesses 6 | WHERE DBID = DB_ID('MyDatatbase') 7 | 8 | PRINT @SQL 9 | --EXEC(@SQL) Replace the print statement with exec to execute -------------------------------------------------------------------------------- /Kill Blocking SPID.sql: -------------------------------------------------------------------------------- 1 | 2 | -- check for blocking 3 | use master 4 | select distinct(blocked) from sysprocesses where blocked <> 0 5 | 6 | -- check if the blocking is blocked 7 | select blocked from sysprocesses where spid = 8 | 9 | -- check the command 10 | dbcc inputbuffer (106) -- change the spid to blocker 11 | 12 | -- if the blocker executing a select statement the spid can be safely killed 13 | kill 106 -- change the spid to blocker -------------------------------------------------------------------------------- /ListAvailableDMOs_Ch05_PowerOfDynamicManagementViews&Functions.sql: -------------------------------------------------------------------------------- 1 | Use master 2 | 3 | GO 4 | 5 | SELECT [name] , 6 | 7 | CASE [type] 8 | 9 | WHEN 'V' THEN 'DMV' 10 | 11 | WHEN 'IF' THEN 'DMF' 12 | 13 | END AS [DMO Type] 14 | 15 | FROM [sys].[sysobjects] 16 | 17 | WHERE [name] LIKE 'dm_%' 18 | 19 | ORDER BY [name] ; -------------------------------------------------------------------------------- /Local Time and UTC Time.sql: -------------------------------------------------------------------------------- 1 | -- Different ways to get date and time 2 | SELECT SYSDATETIME() AS [SYSDATETIME], SYSDATETIMEOFFSET() AS [SYSDATETIMEOFFSET], 3 | SYSUTCDATETIME() AS [SYSUTCDATETIME], CURRENT_TIMESTAMP AS [CURRENT_TIMESTAMP], 4 | GETDATE() AS [GETDATE], GETUTCDATE() AS [GETUTCDATE]; 5 | 6 | -- SQL Server 2008 and 2008 R2 only 7 | SELECT SYSUTCDATETIME() AS [UTCTime]; 8 | SELECT SYSDATETIMEOFFSET() AS [SysDateTimeOffset]; 9 | SELECT SYSDATETIME() AS [SysDateTime] 10 | 11 | 12 | -- These work in SQL Server 2005 13 | SELECT CURRENT_TIMESTAMP AS [CurrentTime]; 14 | SELECT GETDATE() AS [LocalDate]; 15 | SELECT GETUTCDATE() AS [UTCDate]; 16 | 17 | -- Getting difference between local time and UTC time 18 | -- This works in SQL Server 2005 19 | DECLARE @OffsetValue int; 20 | SET @OffsetValue = (SELECT DATEDIFF(hh, GETUTCDATE(), GETDATE())); 21 | SELECT @OffSetValue AS [TimeOffset]; -------------------------------------------------------------------------------- /Max Memory Setting for 2 clusters running.sql: -------------------------------------------------------------------------------- 1 | -- CONFIGURE REMOTE LINKED SERVE FOR RPC OUT TRUE 2 | use tempdb 3 | CREATE TABLE #tmpServices(ServiceName varchar(255)) 4 | INSERT INTO #tmpServices 5 | exec master..xp_cmdshell 'net start' 6 | SELECT * FROM #tmpServices WHERE ServiceName LIKE '%SQL SERVER%' 7 | 8 | 9 | IF EXISTS(SELECT * FROM #tmpServices WHERE ServiceName LIKE ' SQL Server (SQL2008)') 10 | BEGIN 11 | PRINT '2008 SERVICE RUNNING' 12 | EXEC [FROST\SQL2005].TEMPDB.DBO.DBASetMaxMemory 13 | 14 | END 15 | 16 | DROP TABLE #tmpServices 17 | 18 | 19 | 20 | 21 | EXEC SP_CONFIGURE 'xp_cmdshell',1 22 | GO 23 | RECONFIGURE 24 | GO 25 | EXEC SP_CONFIGURE 'max server memory (MB)', 1024 26 | GO 27 | RECONFIGURE 28 | GO 29 | 30 | 31 | CREATE PROCEDURE dbo.DBASetMaxMemory 32 | AS 33 | 34 | EXEC SP_CONFIGURE 'max server memory (MB)', 512 35 | RECONFIGURE 36 | GO 37 | 38 | - 39 | -------------------------------------------------------------------------------- /OpenSQLServerPort.bat: -------------------------------------------------------------------------------- 1 | @echo ========= SQL Server Ports =================== 2 | @echo Enabling SQLServer default instance port 1433 3 | netsh firewall set portopening TCP 1433 "SQLServer" 4 | @echo Enabling Dedicated Admin Connection port 1434 5 | netsh firewall set portopening TCP 1434 "SQL Admin Connection" 6 | @echo Enabling conventional SQL Server Service Broker port 4022 7 | netsh firewall set portopening TCP 4022 "SQL Service Broker" 8 | @echo Enabling Transact-SQL Debugger/RPC port 135 9 | netsh firewall set portopening TCP 135 "SQL Debugger/RPC" 10 | @echo ========= Analysis Services Ports ============== 11 | @echo Enabling SSAS Default Instance port 2383 12 | netsh firewall set portopening TCP 2383 "Analysis Services" 13 | @echo Enabling SQL Server Browser Service port 2382 14 | netsh firewall set portopening TCP 2382 "SQL Browser" 15 | @echo ========= Misc Applications ============== 16 | @echo Enabling HTTP port 80 17 | netsh firewall set portopening TCP 80 "HTTP" 18 | @echo Enabling SSL port 443 19 | netsh firewall set portopening TCP 443 "SSL" 20 | @echo Enabling port for SQL Server Browser Service's 'Browse' Button 21 | netsh firewall set portopening UDP 1434 "SQL Browser" 22 | @echo Allowing multicast broadcast response on UDP (Browser Service Enumerations OK) 23 | netsh firewall set multicastbroadcastresponse ENABLE -------------------------------------------------------------------------------- /Operator_DBA.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/himadanreddy/SQL-DBA-SCRIPTS/3111841fe0efca6d018929c71d2201506912ddcb/Operator_DBA.sql -------------------------------------------------------------------------------- /OptimalMaxServerMemory_New_Multi-Version.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/himadanreddy/SQL-DBA-SCRIPTS/3111841fe0efca6d018929c71d2201506912ddcb/OptimalMaxServerMemory_New_Multi-Version.sql -------------------------------------------------------------------------------- /PBMViewEnabledPoliciesScript_Ch10_PolicyBasedManagement.sql: -------------------------------------------------------------------------------- 1 | /* Healthy SQL - Chapter 10 - Surviving the Audit - Policy Based Management (PBM) - 2 | please run these separately as needed and refer to the book for proper context and run instructions */ 3 | 4 | /*Run to see currently enabled policies*/ 5 | 6 | SELECT name 7 | , description, date_created 8 | FROM msdb.dbo.syspolicy_policies 9 | order by date_created desc 10 | 11 | -------------------------------------------------------------------------------- /PKtoFK.sql: -------------------------------------------------------------------------------- 1 | SELECT 'PK_Table_Schema'=ccu.table_schema, 2 | 'PK_Table_Name'=ccu.table_name, 3 | 'PK_Column_Name'=ccu.column_name, 4 | 'PK_Constraint_Name'=ccu.constraint_name, 5 | 'FK_Table_Schema'=ccu1.table_schema, 6 | 'FK_Table_Name'=ccu1.table_name, 7 | 'FK_Column_Name'=ccu1.column_name, 8 | 'FK_Constraint_Name'=rc.constraint_name 9 | FROM information_schema.constraint_column_usage AS CCU 10 | inner join information_schema.referential_constraints AS RC 11 | ON CCU.constraint_name=RC.unique_constraint_name 12 | inner join information_schema.constraint_column_usage AS CCU1 13 | ON RC.constraint_name=ccu1.constraint_name 14 | WHERE ccu.constraint_name not in 15 | (SELECT constraint_name 16 | FROM information_schema.referential_constraints) 17 | -------------------------------------------------------------------------------- /P_UPDATESTATISTICS.sql: -------------------------------------------------------------------------------- 1 | USE [DBAMaint] 2 | GO 3 | 4 | IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[P_UPDATESTATISTICS]') AND type IN (N'U')) 5 | DROP PROCEDURE [dbo].[P_UPDATESTATISTICS] 6 | 7 | SET ANSI_NULLS ON 8 | GO 9 | 10 | SET QUOTED_IDENTIFIER ON 11 | GO 12 | 13 | 14 | 15 | CREATE PROCEDURE [dbo].[P_UPDATESTATISTICS] 16 | -- Add the parameters for the stored procedure here 17 | 18 | AS 19 | 20 | BEGIN 21 | 22 | SET NOCOUNT ON 23 | 24 | DECLARE @DB_TABLE TABLE (DB NVARCHAR(100)) 25 | DECLARE @DB AS NVARCHAR(100) 26 | DECLARE @COUNTER INT 27 | DECLARE @COMMAND AS NVARCHAR(500) 28 | 29 | INSERT INTO @DB_TABLE (DB) 30 | SELECT [NAME] FROM SYS.DATABASES WHERE name NOT IN ('master','model','msdb','tempdb') 31 | --SELECT * FROM @DB_TABLE AS [@DB_TABLE] 32 | 33 | SET @COUNTER = (SELECT COUNT(*) FROM @DB_TABLE) 34 | --SELECT @COUNTER AS [@COUNTER] 35 | 36 | SET @DB = (SELECT TOP 1 DB FROM @DB_TABLE) 37 | --SELECT @DB 38 | 39 | WHILE @COUNTER > 0 40 | BEGIN 41 | SET @COMMAND = 'USE ['+RTRIM(@DB)+'] EXEC sp_updatestats' 42 | --PRINT @COMMAND 43 | EXEC (@COMMAND) 44 | DELETE FROM @DB_TABLE WHERE DB = @DB 45 | SET @DB = (SELECT TOP 1 DB FROM @DB_TABLE) 46 | 47 | SET @COUNTER = @COUNTER - 1 48 | END 49 | 50 | 51 | 52 | END 53 | 54 | 55 | 56 | GO 57 | 58 | SET ANSI_NULLS OFF 59 | GO 60 | 61 | SET QUOTED_IDENTIFIER OFF 62 | GO 63 | -------------------------------------------------------------------------------- /Parse Comma Delimited Values to Table.sql: -------------------------------------------------------------------------------- 1 | -- Parse comma delimited text into table 2 | DECLARE @str VARCHAR(4000) 3 | = '\\nq.corp\shared\Installs\DBAS,\\nq.corp\shared\Devcuts,\\nq.corp\shared\Installs\Licensed Software,\\nq.corp\shared\Installs\DBAS\IDERA 7.4\Client Install' 4 | --= '6,7,7,8,10,12,13,14,16,44,46,47,394,396,417,488,714' 5 | 6 | 7 | Declare @x XML 8 | 9 | SELECT @x = cast(''+ REPLACE(@str,',','')+ '' AS XML) 10 | 11 | 12 | SELECT t.value('.', 'VARCHAR(512)') AS BackupToPath 13 | --SELECT t.value('.', 'int') as inVal 14 | 15 | FROM @x.nodes('/A') AS x(t) 16 | 17 | 18 | -------------------------------------------------------------------------------- /Partition to FileGroup mapping.sql: -------------------------------------------------------------------------------- 1 | -- Find Partition to FileGroup mappings 2 | SELECT 3 | DestinationId = DestinationDataSpaces.destination_id , 4 | FilegroupName = Filegroups.name , 5 | PartitionHighBoundaryValue = PartitionRangeValues.value , 6 | IsNextUsed = 7 | CASE 8 | WHEN 9 | DestinationDataSpaces.destination_id > 1 10 | AND 11 | LAG (PartitionRangeValues.value , 1) OVER (ORDER BY DestinationDataSpaces.destination_id ASC) IS NULL 12 | THEN 13 | 1 14 | ELSE 15 | 0 16 | END 17 | FROM sys.partition_schemes AS PartitionSchemes 18 | INNER JOIN sys.destination_data_spaces AS DestinationDataSpaces ON PartitionSchemes.data_space_id = DestinationDataSpaces.partition_scheme_id 19 | INNER JOIN sys.filegroups AS Filegroups ON DestinationDataSpaces.data_space_id = Filegroups.data_space_id 20 | LEFT OUTER JOIN sys.partition_range_values AS PartitionRangeValues ON PartitionSchemes.function_id = PartitionRangeValues.function_id 21 | AND DestinationDataSpaces.destination_id = PartitionRangeValues.boundary_id 22 | WHERE PartitionSchemes.name = N'YourPartitionScheme' 23 | ORDER BY DestinationId ASC; 24 | -------------------------------------------------------------------------------- /Partitioning Key.sql: -------------------------------------------------------------------------------- 1 | with partitionedtables AS ( 2 | SELECT DISTINCT 3 | t.object_id, 4 | t.name AS table_name 5 | FROM sys.tables AS t 6 | JOIN sys.indexes AS si on t.object_id=si.object_id 7 | JOIN sys.partition_schemes AS sc on si.data_space_id=sc.data_space_id 8 | ) 9 | SELECT 10 | pt.table_name, 11 | si.index_id, 12 | si.name AS index_name, 13 | ISNULL(pf.name, 'NonAligned') AS partition_function, 14 | ISNULL(sc.name, fg.name) AS partition_scheme_or_filegroup, 15 | ic.partition_ordinal, /* 0= not a partitioning column*/ 16 | ic.key_ordinal, 17 | ic.is_included_column, 18 | c.name AS column_name, 19 | t.name AS data_type_name, 20 | c.is_identity, 21 | ic.is_descending_key, 22 | si.filter_definition 23 | FROM partitionedtables AS pt 24 | JOIN sys.indexes AS si on pt.object_id=si.object_id 25 | JOIN sys.index_columns AS ic on si.object_id=ic.object_id 26 | and si.index_id=ic.index_id 27 | JOIN sys.columns AS c on ic.object_id=c.object_id 28 | and ic.column_id=c.column_id 29 | JOIN sys.types AS t on c.system_type_id=t.system_type_id 30 | LEFT JOIN sys.partition_schemes AS sc on si.data_space_id=sc.data_space_id 31 | LEFT JOIN sys.partition_functions AS pf on sc.function_id=pf.function_id 32 | LEFT JOIN sys.filegroups as fg on si.data_space_id=fg.data_space_id 33 | ORDER BY 1,2,3,4,5,6 DESC,7,8 34 | GO -------------------------------------------------------------------------------- /QuerySystemHeathSessionForErrors_Ch08_MonitoringErrorsWithExtendedEvents.sql: -------------------------------------------------------------------------------- 1 | SELECT CAST(target_data as xml) AS targetdata 2 | INTO #system_health_data 3 | FROM sys.dm_xe_session_targets xet 4 | JOIN sys.dm_xe_sessions xe 5 | ON xe.address = xet.event_session_address 6 | WHERE name = 'system_health' 7 | AND xet.target_name = 'ring_buffer'; 8 | SELECT 9 | DATEADD(mi, DATEDIFF(mi, GETUTCDATE(), CURRENT_TIMESTAMP), xevents.event_data.value 10 | ('(@timestamp)[1]', 'datetime2')) AS [err timestamp], 11 | xevents.event_data.value('(data[@name="severity"]/value)[1]', 'bigint') 12 | AS [err severity], 13 | xevents.event_data.value('(data[@name="error_number"]/value)[1]', 'bigint') 14 | AS [err number], 15 | xevents.event_data.value('(data[@name="message"]/value)[1]', 'nvarchar(512)') 16 | AS [err message], 17 | xevents.event_data.value('(action/value)[2]', 'varchar(10)') as [session id], 18 | xevents.event_data.value('(action[@name="sql_text"]/value)[1]', 'nvarchar(max)') 19 | AS [query text], 20 | xevents.event_data.query('.') as [event details] 21 | FROM #system_health_data 22 | CROSS APPLY targetdata.nodes('//RingBufferTarget/event') AS xevents (event_data) 23 | WHERE xevents.event_data.value('(@name)[1]', 'nvarchar(256)')='error_reported'; 24 | DROP TABLE #system_health_data; 25 | GO -------------------------------------------------------------------------------- /QuickIdxFrag_Chap04_IndexFragmentation.sql: -------------------------------------------------------------------------------- 1 | SELECT * INTO dbo.INDEX_FRAG_STATS FROM sys.dm_db_index_physical_stats (5, NULL, NULL, NULL , 'LIMITED') 2 | 3 | SELECT t.database_id, s.name, s.type,t.object_id, t.index_type_desc, t.avg_fragmentation_in_percent, t.page_count 4 | 5 | FROM dbo.INDEX_FRAG_STATS t inner join sysobjects s on t.[OBJECT_ID] = s.id 6 | 7 | order by t.avg_fragmentation_in_percent desc 8 | 9 | Drop Table dbo.INDEX_FRAG_STATS -------------------------------------------------------------------------------- /ReIndexScript.sql: -------------------------------------------------------------------------------- 1 | --Run this command to display the fragmentation for the database 2 | --DBCC Showcontig with tableresults, All_Indexes 3 | 4 | --Run this query to perform the re-index. 5 | /* 6 | DECLARE @TableName varchar(100) 7 | DECLARE @StartTime datetime 8 | DECLARE @TotalTime int 9 | DECLARE Cur_Tables CURSOR FOR 10 | SELECT [Name] from sysobjects 11 | WHERE OBJECTPROPERTY(id, N'IsUserTable') = 1 12 | AND NAME != 'dtproperties' 13 | AND NAME != 'VisitorPageHits' --Uncomment these entries for exclusions 14 | AND NAME != 'VisitorSessions' 15 | Order By [Name] Asc 16 | OPEN Cur_Tables 17 | FETCH NEXT FROM Cur_Tables 18 | INTO @TableName 19 | WHILE @@FETCH_STATUS = 0 20 | BEGIN 21 | SET @StartTime = GetDate() 22 | DBCC DBREINDEX (@TableName, '', 0) WITH NO_INFOMSGS 23 | SET @TotalTime = DATEDIFF(ss, @StartTime, GetDate()) 24 | Print 'Re-indexing of ' + @TableName + ' took ' + CAST(@TotalTime AS varchar(20)) + ' seconds.' 25 | FETCH NEXT FROM Cur_Tables 26 | INTO @TableName 27 | END 28 | CLOSE Cur_Tables 29 | DEALLOCATE Cur_Tables 30 | GO 31 | */ -------------------------------------------------------------------------------- /Rebuild All Indexes On Single Table SQL2005.sql: -------------------------------------------------------------------------------- 1 | 2 | ALTER INDEX ALL ON dbo.VisitorAgentProspects 3 | REBUILD WITH (FILLFACTOR = 80, SORT_IN_TEMPDB = ON, 4 | STATISTICS_NORECOMPUTE = ON); 5 | GO -------------------------------------------------------------------------------- /Rebuild All Indexes On Single Table.sql: -------------------------------------------------------------------------------- 1 | ALTER INDEX ALL ON [dbo].[PortfolioLeadCap] 2 | REBUILD WITH (FILLFACTOR = 80, SORT_IN_TEMPDB = ON, 3 | STATISTICS_NORECOMPUTE = ON); 4 | GO 5 | -------------------------------------------------------------------------------- /Rebuild Indexes Using Cursor.sql: -------------------------------------------------------------------------------- 1 | Declare @TableName VarChar(100), @SQL VarChar(1000) 2 | Declare Cur_Tables Cursor For 3 | Select Name From sys.objects 4 | Where ObjectProperty(Object_ID, 'IsUserTable') = 1 5 | And ObjectProperty(Object_ID, 'IsView') = 0 6 | And ObjectProperty(Object_ID, 'TableHasIndex') = 1 7 | And Name != 'dtproperties' 8 | Order By Name Asc 9 | Open Cur_Tables 10 | Fetch Next From Cur_Tables 11 | InTo @TableName 12 | While @@Fetch_Status = 0 13 | Begin 14 | Set @SQL = 'Alter Index All On ' + @TableName + ' Rebuild With (MAXDOP = 1)' 15 | Exec(@SQL) 16 | FETCH NEXT FROM Cur_Tables 17 | INTO @TableName 18 | END 19 | CLOSE Cur_Tables 20 | DEALLOCATE Cur_Tables 21 | GO -------------------------------------------------------------------------------- /Redeploy ServiceContractMove CLR Store Proc TO CP.sql: -------------------------------------------------------------------------------- 1 | 2 | -- DISABLE THE JOB NAMED CP_Move_ServiceContracts CLR PROC AND WAIT IF IT'S RUNNING TO COMPLETE 3 | 4 | -- 1. Drop CLR stored proc 5 | -- 2. Drop Assembly 6 | -- 3. Backup and Delete old DLL file 7 | -- 4. Copy the new DLL to the location on hard drive 8 | -- 5. Create Assembly 9 | -- 6. Create Stored Procedure 10 | 11 | 12 | -- 1 13 | USE [BackOfficeCurrentProduction] 14 | GO 15 | DROP PROCEDURE dbo.ServiceContractMove 16 | 17 | -- 2 18 | USE [BackOfficeCurrentProduction] 19 | GO 20 | DROP ASSEMBLY [ServiceContractsMovement] 21 | 22 | -- 3 23 | -- BACKUP OR DELETE OLD DLL 24 | 25 | -- 4 26 | -- COPY THE NEW DLL 27 | 28 | -- 5 29 | USE [BackOfficeCurrentProduction] 30 | GO 31 | ALTER AUTHORIZATION ON DATABASE::BackOfficeCurrentProduction TO SA; 32 | GO 33 | 34 | ALTER DATABASE BackOfficeCurrentProduction SET TRUSTWORTHY ON; 35 | GO 36 | CREATE ASSEMBLY [ServiceContractsMovement] 37 | AUTHORIZATION [dbo] 38 | FROM 'F:\ServiceContracts\CurrentProduction\ServiceContractsMovement.dll' 39 | WITH PERMISSION_SET = UNSAFE; 40 | 41 | GO 42 | USE [BackOfficeCurrentProduction] 43 | GO 44 | SET ANSI_NULLS ON 45 | GO 46 | SET QUOTED_IDENTIFIER ON 47 | GO 48 | CREATE PROCEDURE dbo.ServiceContractMove 49 | @minuteDelay INT 50 | AS 51 | EXTERNAL NAME [ServiceContractsMovement].[ServiceContractsMovement.StoredProcedures].[ServiceContractMove] 52 | 53 | GO -------------------------------------------------------------------------------- /Remove Spaces and Colons From Date.sql: -------------------------------------------------------------------------------- 1 | SELECT SUBSTRING(REPLACE(REPLACE((REPLACE((CONVERT(VARCHAR(32), CURRENT_TIMESTAMP, 120)), '-', '')), ':', ''), ' ', ''), 1, 12) -------------------------------------------------------------------------------- /Rename Database.sql: -------------------------------------------------------------------------------- 1 | USE master; 2 | GO 3 | ALTER DATABASE Advatar SET OFFLINE WITH ROLLBACK IMMEDIATE 4 | GO 5 | ALTER DATABASE Advatar SET ONLINE 6 | GO 7 | ALTER DATABASE Advatar 8 | Modify Name = Advatar_OLD ; 9 | GO 10 | 11 | ALTER DATABASE Advatar_DISH SET OFFLINE WITH ROLLBACK IMMEDIATE 12 | GO 13 | ALTER DATABASE Advatar_DISH SET ONLINE 14 | GO 15 | ALTER DATABASE Advatar_DISH 16 | Modify Name = Advatar ; 17 | GO 18 | -------------------------------------------------------------------------------- /Rename SA account.sql: -------------------------------------------------------------------------------- 1 | 2 | ALTER LOGIN [sa] WITH NAME = [somethingobnoxiouslyhardtofigureout_dontuse_sa2] 3 | 4 | -------------------------------------------------------------------------------- /ReplicationLogReaderMonitorCode.sql: -------------------------------------------------------------------------------- 1 | USE distribution 2 | go 3 | SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED 4 | SELECT ma2.publisher_db, 5 | mh1.delivery_latency / ( 1000 * 60 ) AS delivery_latency_Minutes, 6 | mh1.agent_id , 7 | mh1.time, 8 | CAST(mh1.comments AS XML) AS comments, 9 | CASE mh1.runstatus 10 | WHEN 1 THEN 'Start' 11 | WHEN 2 THEN 'Succeed.' 12 | WHEN 3 THEN 'In progress.' 13 | WHEN 4 THEN 'Idle.' 14 | WHEN 5 THEN 'Retry.' 15 | WHEN 6 THEN 'Fail' 16 | END AS Status, 17 | mh1.duration, 18 | mh1.xact_seqno, 19 | mh1.delivered_transactions, 20 | mh1.delivered_commands, 21 | mh1.average_commands, 22 | mh1.delivery_time, 23 | mh1.delivery_rate, 24 | ma2.name as jobname 25 | FROM mslogreader_history mh1 26 | JOIN ( 27 | SELECT mh1.agent_id, MAX(mh1.time) as maxtime 28 | FROM mslogreader_history mh1 29 | JOIN MSlogreader_agents ma on ma.id = mh1.agent_id 30 | GROUP BY mh1.agent_id) AS mh2 ON mh1.agent_id = mh2.agent_id and mh1.time = mh2.maxtime 31 | JOIN MSlogreader_agents ma2 on ma2.id = mh2.agent_id 32 | ORDER BY mh1.delivery_latency desc -------------------------------------------------------------------------------- /Restore Database From Database Snapshot.sql: -------------------------------------------------------------------------------- 1 | USE master; 2 | GO 3 | 4 | ALTER DATABASE Advatar SET OFFLINE WITH ROLLBACK IMMEDIATE; 5 | GO 6 | 7 | ALTER DATABASE Advatar SET ONLINE; 8 | GO 9 | 10 | -- Reverting AdventureWorks to AdventureWorks_dbss1800 11 | RESTORE DATABASE Advatar FROM 12 | DATABASE_SNAPSHOT = 'Advatar_SnapShot_20161006_1302'; 13 | GO 14 | -------------------------------------------------------------------------------- /Review Locks.sql: -------------------------------------------------------------------------------- 1 | SELECT resource_type 2 | ,(CASE 3 | WHEN resource_type = 'OBJECT' THEN object_name(resource_associated_entity_id) 4 | WHEN resource_type IN ('DATABASE', 'FILE', 'METADATA') THEN 'N/A' 5 | WHEN resource_type IN ('KEY', 'PAGE', 'RID') THEN ( 6 | SELECT 7 | object_name(object_id) 8 | FROM 9 | sys.partitions 10 | WHERE 11 | hobt_id=resource_associated_entity_id) 12 | ELSE 'Undefined' 13 | END) AS resource_name 14 | ,request_mode as lock_type 15 | ,resource_description 16 | ,request_status 17 | ,request_session_id 18 | ,request_owner_id AS transaction_id 19 | 20 | FROM sys.dm_tran_locks 21 | WHERE resource_type <> 'DATABASE'; -------------------------------------------------------------------------------- /Revoke Connect Permission to Guest User.sql: -------------------------------------------------------------------------------- 1 | SET NOCOUNT ON; 2 | DECLARE @SQL nvarchar(2000) 3 | DECLARE @name nvarchar(128) 4 | DECLARE @database_id int 5 | 6 | CREATE TABLE #databases (database_id int NOT NULL, databasename nvarchar(128) NOT NULL, processed bit NOT NULL) 7 | INSERT INTO #databases 8 | (database_id, databasename, processed) 9 | SELECT database_id, name, 0 FROM master.sys.databases WHERE name NOT IN ('master', 'tempdb', 'msdb', 'distribution') 10 | 11 | WHILE (SELECT COUNT(processed) FROM #databases WHERE processed = 0) > 0 12 | BEGIN 13 | SELECT TOP 1 14 | @name = databasename, 15 | @database_id = database_id 16 | FROM #databases 17 | WHERE processed = 0 18 | ORDER BY database_id 19 | 20 | SELECT @SQL = 'USE [' + @name + ']; REVOKE CONNECT TO [GUEST];' 21 | 22 | PRINT @SQL; 23 | 24 | UPDATE #databases SET processed = 1 WHERE database_id = @database_id; 25 | END 26 | 27 | DROP TABLE #databases; 28 | 29 | SET NOCOUNT OFF; -------------------------------------------------------------------------------- /SQL 2005 ALERTS.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/himadanreddy/SQL-DBA-SCRIPTS/3111841fe0efca6d018929c71d2201506912ddcb/SQL 2005 ALERTS.sql -------------------------------------------------------------------------------- /SQL DBA CheckDB Process.doc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/himadanreddy/SQL-DBA-SCRIPTS/3111841fe0efca6d018929c71d2201506912ddcb/SQL DBA CheckDB Process.doc -------------------------------------------------------------------------------- /SQL DBA Deployment Script.doc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/himadanreddy/SQL-DBA-SCRIPTS/3111841fe0efca6d018929c71d2201506912ddcb/SQL DBA Deployment Script.doc -------------------------------------------------------------------------------- /SSB_AZURE_SQL_CLIENT_DW.sql: -------------------------------------------------------------------------------- 1 | --l2oqghb8m9.database.windows.net 2 | --SSBRPProduction 3 | SELECT DISTINCT s.ServerName, ds.FriendlyName, s.FQDN, ds.DBName, d.DBType, ds.Username, ds.EncryptedPassword 4 | FROM dbo.TenantDataSource ds 5 | INNER JOIN dbo.Server s ON ds.ServerID = s.ServerID 6 | INNER JOIN dbo.Tenant t ON ds.TenantID = t.TenantID 7 | INNER JOIN dbo.DBType d ON ds.DBTypeID = d.DBTypeID 8 | WHERE t.Active = 1 9 | AND ds.IsActive = 1 10 | AND ds.EnvTypeID = 'B9DF5979-0D04-42E2-A641-BEB7E1F70A61' -- Production 11 | AND ds.DBTypeID = '0B23D482-99FE-4127-961E-EB5402DEB7DC' -- Client DW 12 | ORDER BY d.DBType, s.FQDN 13 | -------------------------------------------------------------------------------- /SSIS 32_64 bit Reg Unreg DLL.txt: -------------------------------------------------------------------------------- 1 | 64 Bit DLL Folder Location: 2 | 3 | Example --> C:\Program Files\Microsoft SQL Server\90\DTS\Binn 4 | 5 | 32 Bit DLL Folder Location: 6 | 7 | Example --> C:\Program Files (x86)\Microsoft SQL Server\90\DTS\Binn 8 | 9 | 10 | 11 | To run the commands to unregister and register the DLL's go to "Start" / "Run" and enter the following commands below. The DLL's should be unregistered first and then registered. 12 | 13 | To Unregister a 64 Bit DLL use the following command below: 14 | 15 | regsvr32 /u "location of the DLL" ie: regsvr32 /u "C:\Program Files\Microsoft SQL Server\90\DTS\Binn\DTS.dll" 16 | 17 | To Register a 64 Bit DLL use the following command below: 18 | 19 | regsvr32 "location of the DLL" ie: regsvr32 "C:\Program Files\Microsoft SQL Server\90\DTS\Binn\DTS.dll" 20 | 21 | 22 | 23 | To Unregister a 32 Bit DLL use the following command below: 24 | 25 | regsvr32 /u "location of the DLL" ie: regsvr32 /u "C:\Program Files (x86)\Microsoft SQL Server\90\DTS\Binn\DTS.dll" 26 | 27 | To Register a 32 Bit DLL use the following command below: 28 | 29 | regsvr32 "location of the DLL" ie: regsvr32 "C:\Program Files (x86)\Microsoft SQL Server\90\DTS\Binn\DTS.dll" 30 | 31 | 32 | 33 | BIS 8 Key DLL's 34 | 35 | 1. DTS.dll 36 | 2. DTSComExprEval.dll 37 | 3. DtsConn.dll 38 | 4. DTSLog.dll 39 | 5. DTSPipeline.dll 40 | 6. ExecPackageTask.dll 41 | 7. MsDtsSrvrUtil.dll 42 | 8. SQLTaskConnections.dll 43 | -------------------------------------------------------------------------------- /STRING_SPLIT Sample.sql: -------------------------------------------------------------------------------- 1 | DECLARE @A VARCHAR(128) = 'ABCDEF' 2 | SELECT value FROM STRING_SPLIT(CAST(CAST(CAST(@A AS NVARCHAR) AS VARBINARY) AS VARCHAR), CHAR(0)) 3 | 4 | SET @A = 'Water,Coffee,Tea,Milk' 5 | 6 | SELECT Value 7 | FROM STRING_SPLIT(@A, ',') 8 | -------------------------------------------------------------------------------- /Send Email for Service Restarts.sql: -------------------------------------------------------------------------------- 1 | USE msdb 2 | GO 3 | -- Declare variables for necessary email content 4 | DECLARE @ServerName VARCHAR(128), 5 | @ComputerNamePhysicalNetBIOS VARCHAR(128), 6 | @Datetime DATETIME, 7 | @EmailRecipients VARCHAR(512), 8 | @EmailSubject VARCHAR(128), 9 | @MessageBody VARCHAR(512) 10 | 11 | -- Set variables to proper values 12 | SELECT @ComputerNamePhysicalNetBIOS = CAST(SERVERPROPERTY('ComputerNamePhysicalNetBIOS') AS VARCHAR(128)), 13 | @ServerName = CAST(SERVERPROPERTY('ServerName') AS VARCHAR(128)), 14 | @Datetime = GETDATE(), 15 | @EmailRecipients = 'bgucuk@servicesource.com', -- if more than one email address use ; between email addresses 16 | @EmailSubject = 'SQL Server Services Have Been Started!!!' 17 | 18 | SELECT @MessageBody = 'SQL Server services have been started on a SQL Server Instance named ' + @ServerName + CHAR(13) + 19 | 'running on windows server ' + @ComputerNamePhysicalNetBIOS + '.' + CHAR(13) + CHAR(13) + 20 | 'Investigate the service restart if it has not been communicated.' 21 | 22 | EXEC sp_send_dbmail 23 | @recipients = @EmailRecipients, 24 | @subject = @EmailSubject, 25 | @body = @MessageBody, 26 | @body_format = 'TEXT' 27 | -------------------------------------------------------------------------------- /ServiceContractsMovement.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/himadanreddy/SQL-DBA-SCRIPTS/3111841fe0efca6d018929c71d2201506912ddcb/ServiceContractsMovement.dll -------------------------------------------------------------------------------- /Set Default Database for Logins without Default Database.sql: -------------------------------------------------------------------------------- 1 | SELECT SL.name, 2 | SL.dbname, 3 | 'USE [tempdb]; 4 | ALTER LOGIN [' + SL.name + '] WITH DEFAULT_DATABASE=[tempdb]; 5 | CREATE USER [' + SL.name + '] FOR LOGIN [' + SL.name + '] WITH DEFAULT_SCHEMA = [dbo];' AS SQL_command 6 | FROM sys.[syslogins] SL 7 | LEFT JOIN sys.[databases] SD 8 | ON SL.[dbname] = SD.[name] 9 | WHERE SD.name IS NULL 10 | ORDER BY SL.[name], SL.[dbname]; -------------------------------------------------------------------------------- /Split Comma Seperated String Using XML.sql: -------------------------------------------------------------------------------- 1 | DECLARE 2 | @S VARCHAR(512) 3 | , @Split CHAR(1) 4 | , @X XML; 5 | 6 | SELECT 7 | @S = '1,2,3,4,5' 8 | , @Split = ',' ; 9 | 10 | SELECT @X = CONVERT(XML,' ' + REPLACE(@S,@Split,' ') + ' ') 11 | 12 | SELECT [Value] = T.c.value('.','varchar(20)') 13 | FROM @X.nodes('/root/s') T(c); 14 | -------------------------------------------------------------------------------- /Stats Update Date.sql: -------------------------------------------------------------------------------- 1 | --Get the date stats update date 2 | 3 | SELECT name AS index_name, 4 | STATS_DATE(OBJECT_ID, index_id) AS statistics_update_date 5 | FROM sys.indexes 6 | WHERE OBJECT_ID = OBJECT_ID('dbo.Accounts'); -- change the table name -------------------------------------------------------------------------------- /Step 3 Drop Foreign Keys.sql: -------------------------------------------------------------------------------- 1 | USE MYDATABASE -- CHANGE THE NAME OF THE DB 2 | SET NOCOUNT ON 3 | -- DROP FK CONSTRAINTS 4 | DECLARE @MaxFKid INT, 5 | @Str VARCHAR(1024) 6 | 7 | SELECT @MaxFKid = MAX(FKid) 8 | FROM dbo.FKDrop 9 | 10 | WHILE @MaxFKid > 0 11 | BEGIN 12 | SELECT @Str = '' 13 | SELECT @Str = [Str] 14 | FROM dbo.FKDrop 15 | WHERE FKid = @MaxFKid 16 | PRINT @Str 17 | EXEC (@Str) 18 | SELECT @MaxFKid = @MaxFKid - 1 19 | END -------------------------------------------------------------------------------- /Step 4 Create Foreign Keys.sql: -------------------------------------------------------------------------------- 1 | USE MYDATABASE -- CHANGE THE NAME OF THE DB 2 | SET NOCOUNT ON 3 | -- RECREATE FK CONSTRAINTS 4 | DECLARE @MaxFKid INT, 5 | @Str VARCHAR(1024) 6 | 7 | SELECT @MaxFKid = MAX(FKid) 8 | FROM dbo.FKCreate 9 | 10 | WHILE @MaxFKid > 0 11 | BEGIN 12 | SELECT @Str = '' 13 | SELECT @Str = [Str] 14 | FROM dbo.FKCreate 15 | WHERE FKid = @MaxFKid 16 | PRINT @Str 17 | EXEC (@Str) 18 | SELECT @MaxFKid = @MaxFKid - 1 19 | END 20 | -------------------------------------------------------------------------------- /Step 5 Drop Create FK and Drop FK Tables.sql: -------------------------------------------------------------------------------- 1 | USE MYDATABASE -- CHANGE THE NAME OF THE DB 2 | SET NOCOUNT ON 3 | -- DROP FK TABLES NOT NEEDED IN DEVCUT 4 | IF EXISTS ( 5 | SELECT 1 6 | FROM SYS.TABLES 7 | WHERE NAME = 'FKCreate' 8 | ) 9 | BEGIN 10 | TRUNCATE TABLE dbo.FKCreate 11 | DROP TABLE dbo.FKCreate 12 | END 13 | GO 14 | 15 | IF EXISTS ( 16 | SELECT 1 17 | FROM SYS.TABLES 18 | WHERE NAME = 'FKDrop' 19 | ) 20 | BEGIN 21 | TRUNCATE TABLE dbo.FKDrop 22 | DROP TABLE dbo.FKDrop 23 | END 24 | GO -------------------------------------------------------------------------------- /Suspect Pages Alert Monitor.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/himadanreddy/SQL-DBA-SCRIPTS/3111841fe0efca6d018929c71d2201506912ddcb/Suspect Pages Alert Monitor.sql -------------------------------------------------------------------------------- /System.Core.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/himadanreddy/SQL-DBA-SCRIPTS/3111841fe0efca6d018929c71d2201506912ddcb/System.Core.dll -------------------------------------------------------------------------------- /TSA BCP TEST.sql: -------------------------------------------------------------------------------- 1 | select suser_name() 2 | exec [dbo].[sp_PMS_SelectTSAReport] 3 | @StartDate = '06/01/2008', 4 | @EndDate = '06/02/2008', 5 | @OutPutFile = '\\netquote\shared\BatchDeliveries\TSA\Production\tsa-netquote-BG-TEST.csv', 6 | @Separator = ',' 7 | 8 | -- old folder 9 | -- \\netquote\shared\TSA-Production$ 10 | -- new folder 11 | -- \\netquote\shared\BatchDeliveries\TSA\Production 12 | 13 | DECLARE 14 | @StartDate DateTime, 15 | @EndDate DateTime, 16 | @OutPutFile Varchar(400), 17 | @Separator Varchar(1) 18 | 19 | DECLARE @DBName varchar(100) 20 | DECLARE @CMD VarChar(4000) 21 | 22 | DECLARE @Error_List TABLE 23 | ( 24 | Error varchar (255) 25 | ) 26 | 27 | SELECT @DBName = db_name() 28 | 29 | SET @StartDate = '04/06/2008' 30 | SET @EndDate = '04/07/2008' 31 | SET @OutPutFile = '\\netquote\shared\TSA-Production$\tsa-netquote-BG-TEST.csv' 32 | SET @Separator = ',' 33 | 34 | 35 | SET @CMD = 'bcp "' + @DBName + '.dbo.TMP_TsaReport" out "' + @OutPutFile + '" -t"\' + @Separator + '" -c -S' + @@ServerName + ' -T'--U Netquote0\tsaaccount -P pNUn82Er' 36 | 37 | 38 | PRINT @CMD 39 | 40 | INSERT @Error_List (Error) 41 | SELECT * FROM @Error_List 42 | 43 | Exec master.dbo.xp_cmdshell @CMD 44 | 45 | --SSC example 46 | C:\>bcp.exe "exec [AdventureWorks].[dbo].[uspGetEmployeeManagers] @EmployeeID = 153" queryout "c:\EmployeeManagers.txt" 47 | -SCFEDERL -T -c -------------------------------------------------------------------------------- /Testresult1.txt: -------------------------------------------------------------------------------- 1 | sqlio v1.5.SG 2 | using system counter for latency timings, 2467812 counts per second 3 | parameter file used: param.txt 4 | file c:\testfile.dat with 2 threads (0-1) using mask 0x0 (0) 5 | 2 threads writing for 120 secs to file c:\testfile.dat 6 | using 64KB random IOs 7 | enabling multiple I/Os per thread with 1 outstanding 8 | buffering set to use hardware disk cache (but not file cache) 9 | size of file c:\testfile.dat needs to be: 2147483648 bytes 10 | current file size: 0 bytes 11 | need to expand by: 2147483648 bytes 12 | expanding c:\testfile.dat ... done. 13 | using specified size: 2048 MB for file: c:\testfile.dat 14 | initialization done 15 | CUMULATIVE DATA: 16 | throughput metrics: 17 | IOs/sec: 2198.45 18 | MBs/sec: 137.40 19 | latency metrics: 20 | Min_Latency(ms): 0 21 | Avg_Latency(ms): 0 22 | Max_Latency(ms): 28 23 | histogram: 24 | ms: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24+ 25 | %: 84 12 4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 26 | -------------------------------------------------------------------------------- /Top Waits.sql: -------------------------------------------------------------------------------- 1 | -- Clear Wait Stats 2 | --DBCC SQLPERF('sys.dm_os_wait_stats', CLEAR); 3 | 4 | 5 | -- Isolate top waits 6 | WITH Waits AS 7 | ( 8 | SELECT 9 | wait_type, 10 | wait_time_ms / 1000. AS wait_time_s, 11 | 100. * wait_time_ms / SUM(wait_time_ms) OVER() AS pct, 12 | ROW_NUMBER() OVER(ORDER BY wait_time_ms DESC) AS rn 13 | FROM sys.dm_os_wait_stats 14 | WHERE wait_type NOT LIKE '%SLEEP%' 15 | -- filter out additional irrelevant waits 16 | ) 17 | SELECT 18 | W1.wait_type, 19 | CAST(W1.wait_time_s AS DECIMAL(12, 2)) AS wait_time_s, 20 | CAST(W1.pct AS DECIMAL(12, 2)) AS pct, 21 | CAST(SUM(W2.pct) AS DECIMAL(12, 2)) AS running_pct 22 | FROM Waits AS W1 23 | INNER JOIN Waits AS W2 24 | ON W2.rn <= W1.rn 25 | GROUP BY W1.rn, W1.wait_type, W1.wait_time_s, W1.pct 26 | HAVING SUM(W2.pct) - W1.pct < 90 -- percentage threshold 27 | ORDER BY W1.rn; -------------------------------------------------------------------------------- /Top of The Hour.sql: -------------------------------------------------------------------------------- 1 | 2 | 3 | select DATEADD(HH, DATEDIFF(HH, 0, GETDATE()), 0) -- current hour top of the hour 4 | 5 | select DATEADD(HH, (DATEDIFF(HH, 0, GETDATE()))-2, 0) -- 2 hours ago top of the hour -------------------------------------------------------------------------------- /TransLogMonitor Table.sql: -------------------------------------------------------------------------------- 1 | USE DBA; 2 | GO 3 | 4 | /****** Object: Table [dbo].[TransLogMonitor] Script Date: 5/27/2017 4:40:13 PM ******/ 5 | SET ANSI_NULLS ON 6 | GO 7 | 8 | SET QUOTED_IDENTIFIER ON 9 | GO 10 | 11 | IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TransLogMonitor]') AND type in (N'U')) 12 | BEGIN 13 | CREATE TABLE [dbo].[TransLogMonitor]( 14 | [LogID] [int] IDENTITY(1,1) NOT NULL, 15 | [LogDate] [datetime] NOT NULL, 16 | [DatabaseName] [varchar](100) NOT NULL, 17 | [LogSizeMB] [decimal](18, 2) NOT NULL, 18 | [LogSpaceUsed] [decimal](18, 2) NOT NULL, 19 | [Status] [int] NOT NULL, 20 | [VLF_count] [int] NULL, 21 | CONSTRAINT [PK_TransLogMonitor_LogID] PRIMARY KEY CLUSTERED 22 | ( 23 | [LogID] ASC 24 | )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 100, DATA_COMPRESSION = PAGE) ON [PRIMARY] 25 | ) ON [PRIMARY] 26 | END 27 | GO 28 | 29 | IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DF_TransLogMonitor_LogDate]') AND type = 'D') 30 | BEGIN 31 | ALTER TABLE [dbo].[TransLogMonitor] ADD CONSTRAINT [DF_TransLogMonitor_LogDate] DEFAULT (getdate()) FOR [LogDate] 32 | END 33 | 34 | GO 35 | -------------------------------------------------------------------------------- /Trap xp_cmdshell Error Message and Raiserror.sql: -------------------------------------------------------------------------------- 1 | SET NOCOUNT ON 2 | DECLARE @cmdline VARCHAR(500), 3 | @ReturnCode INT, 4 | @ErrorMessage varchar(500) 5 | 6 | --Command to execute 7 | SELECT @cmdline ='Net use \\DPBack0050\RepToBP15d\DQDBXX0050_QA01 Kv5apmENxb /USER:web.prod\IUSR_SQL_SERVICE /PERSISTENT:YES'; 8 | 9 | --Create temp table to hold result 10 | CREATE TABLE #CmdShellLog (CmdShellMessage VARCHAR(500) NULL) 11 | 12 | --dump result into temp table 13 | INSERT #CmdShellLog 14 | EXEC @ReturnCode = master.dbo.xp_cmdshell @cmdline 15 | 16 | -- If we have an error populate variable 17 | IF @ReturnCode <> 0 18 | BEGIN 19 | SELECT @ErrorMessage = CmdShellMessage 20 | FROM #CmdShellLog 21 | WHERE CmdShellMessage IS NOT NULL 22 | 23 | --Display error message and return code 24 | SELECT @ErrorMessage as ErrorMessage ,@ReturnCode as ReturnCode 25 | 26 | RAISERROR(@ErrorMessage,16,1) 27 | 28 | END 29 | ELSE 30 | BEGIN 31 | -- statement to run 32 | PRINT 'IF XP_CMDSHELL IS SUCCESS YOU SHOULD SEE THIS' 33 | 34 | END 35 | 36 | -- drop temp table 37 | DROP TABLE #CmdShellLog -------------------------------------------------------------------------------- /Try Catch Block with Commit RollBack Trx and Raise Error Short.sql: -------------------------------------------------------------------------------- 1 | SET XACT_ABORT ON; 2 | SET NOCOUNT ON; 3 | BEGIN TRY 4 | BEGIN TRANSACTION; 5 | -- SQL statement goes here 6 | 7 | 8 | 9 | 10 | -- If statement succeeds, commit the transaction. 11 | COMMIT TRANSACTION; 12 | 13 | END TRY 14 | BEGIN CATCH 15 | DECLARE 16 | @ErrorMessage NVARCHAR(4000) 17 | , @ErrorSeverity INT 18 | , @ErrorState INT; 19 | 20 | SELECT 21 | @ErrorMessage = ERROR_MESSAGE() 22 | , @ErrorSeverity = ERROR_SEVERITY() 23 | , @ErrorState = ERROR_STATE(); 24 | 25 | -- Test XACT_STATE for 0, 1, or -1. 26 | -- If 1, the transaction is committable. 27 | -- If -1, the transaction is uncommittable and should be rolled back. 28 | -- If 0 means there is no transaction and a commit or rollback operation would generate an error. 29 | 30 | -- Test whether the transaction is uncommittable. 31 | IF (XACT_STATE()) = -1 32 | BEGIN 33 | ROLLBACK TRANSACTION; 34 | END; 35 | 36 | -- Test whether the transaction is active and valid. 37 | IF (XACT_STATE()) = 1 38 | BEGIN 39 | COMMIT TRANSACTION; 40 | END; 41 | 42 | -- RAISERROR 43 | RAISERROR(@ErrorMessage,@ErrorSeverity,@ErrorState); 44 | 45 | END CATCH; 46 | GO -------------------------------------------------------------------------------- /Try Catch Block with Commit RollBack Trx and Throw Error Short.sql: -------------------------------------------------------------------------------- 1 | SET XACT_ABORT ON; 2 | SET NOCOUNT ON; 3 | BEGIN TRY 4 | BEGIN TRANSACTION; 5 | -- SQL statement goes here 6 | 7 | 8 | 9 | 10 | -- If statement succeeds, commit the transaction. 11 | COMMIT TRANSACTION; 12 | 13 | END TRY 14 | BEGIN CATCH 15 | DECLARE 16 | @ErrorMessage NVARCHAR(4000) 17 | , @ErrorSeverity INT 18 | , @ErrorState INT 19 | , @ErrorNumber INT; 20 | 21 | SELECT 22 | @ErrorMessage = ERROR_MESSAGE() 23 | , @ErrorSeverity = ERROR_SEVERITY() 24 | , @ErrorState = ERROR_STATE() 25 | , @ErrorNumber = ERROR_NUMBER(); 26 | 27 | -- Test XACT_STATE for 0, 1, or -1. 28 | -- If 1, the transaction is committable. 29 | -- If -1, the transaction is uncommittable and should be rolled back. 30 | -- If 0 means there is no transaction and a commit or rollback operation would generate an error. 31 | 32 | -- Test whether the transaction is uncommittable. 33 | IF (XACT_STATE()) = -1 34 | BEGIN 35 | ROLLBACK TRANSACTION; 36 | END; 37 | 38 | -- Test whether the transaction is active and valid. 39 | IF (XACT_STATE()) = 1 40 | BEGIN 41 | COMMIT TRANSACTION; 42 | END; 43 | 44 | -- THROW ERROR 45 | THROW; 46 | 47 | END CATCH; 48 | GO 49 | -------------------------------------------------------------------------------- /TurnOnTDE.sql: -------------------------------------------------------------------------------- 1 | -- 2 | -- SQL 2008 TDE Setup and Administration 3 | -- 4 | -- Turn on XX_DATABASE_XX TDE encryption assuming it is already setup for server 5 | -- 6 | -- Sean Elliott 7 | -- sean_p_elliott@yahoo.co.uk 8 | -- 9 | -- February 2011 10 | -- 11 | 12 | declare @DateStr varchar(32) 13 | 14 | print 'Switching on XX_DATABASE_XX data encryption via TDE' 15 | use XX_DATABASE_XX 16 | alter database XX_DATABASE_XX set encryption on 17 | 18 | -- Let user know when encryption has completed 19 | while not exists 20 | ( 21 | select encryption_state from sys.dm_database_encryption_keys 22 | where DB_NAME(database_id) = 'XX_DATABASE_XX' and encryption_state = 3 23 | ) 24 | begin 25 | set @DateStr = convert(varchar, getdate(), 120) 26 | raiserror('%s Waiting 5 seconds for database encryption to complete', 0, 0, @DateStr) with nowait 27 | waitfor delay '00:00:05' 28 | end 29 | 30 | print 'Encryption complete' 31 | 32 | select db_name(database_id), 33 | case encryption_state 34 | when 0 then '0 - No database encryption key present, no encryption' 35 | when 1 then '1 - Unencrypted' 36 | when 2 then '2 - Encryption in progress' 37 | when 3 then '3 - Encrypted' 38 | when 4 then '4 - Key change in progress' 39 | when 5 then '5 - Decryption in progress' 40 | end encryption_state_desc, 41 | * 42 | from sys.dm_database_encryption_keys 43 | -------------------------------------------------------------------------------- /Update Job Owner To SA.sql: -------------------------------------------------------------------------------- 1 | USE MSDB; 2 | GO 3 | SET NOCOUNT ON; 4 | /******************************** 5 | 6 | This script is used to update the job owner to sa for 7 | the jobs that is not already owned by sa. 8 | 9 | ********************************/ 10 | DECLARE 11 | @MinRowId INT = 1 12 | , @MaxRowId INT 13 | , @jobId UNIQUEIDENTIFIER 14 | , @owner_login_name NVARCHAR(128) = N'sa'; 15 | 16 | -- Store the job steps in a temp table to update the in the loop later 17 | IF OBJECT_ID('tempdb..#Jobs') IS NOT NULL 18 | DROP TABLE #Jobs; 19 | CREATE TABLE #Jobs ( 20 | RowId INT IDENTITY (1,1) NOT NULL 21 | , job_id UNIQUEIDENTIFIER NOT NULL 22 | , jobname SYSNAME NOT NULL 23 | , owner_sid VARBINARY(85) 24 | ); 25 | 26 | INSERT INTO #Jobs (job_id, jobname, owner_sid ) 27 | SELECT j.job_id, j.name, j.owner_sid 28 | FROM dbo.sysjobs AS j 29 | WHERE J.owner_sid <> 0x01 -- sid for SA 30 | ORDER BY j.name 31 | 32 | SET @MaxRowId = @@ROWCOUNT; 33 | 34 | WHILE @MinRowId <= @MaxRowId 35 | BEGIN 36 | SELECT @jobId = job_id 37 | FROM #Jobs 38 | WHERE RowId = @MinRowId; 39 | 40 | EXEC sp_update_job @job_id = @jobId, @owner_login_name = @owner_login_name; 41 | 42 | SET @MinRowId = @MinRowId + 1; 43 | END 44 | --Return list of jobs and original owner sid 45 | SELECT * FROM #Jobs; 46 | DROP TABLE #Jobs; -------------------------------------------------------------------------------- /Update Using Two Table Join.sql: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | UPDATE NETQUOTE.DBO.PendingApplications 4 | SET APPLICATIONSTATUSID = T.APPLICATIONSTATUSID 5 | FROM TAIPEI.NetQuoteWebsite.DBO.PendingApplications AS T 6 | INNER JOIN NETQUOTE.DBO.PendingApplications 7 | ON NETQUOTE.DBO.PendingApplications.APPLICATIONID = T.APPLICATIONID 8 | WHERE NETQUOTE.DBO.PendingApplications.APPLICATIONID = T.APPLICATIONID 9 | (1163531 row(s) affected) 10 | */ 11 | 12 | UPDATE NETQUOTE.DBO.PendingApplications 13 | SET BrandId = T.BrandId 14 | FROM TAIPEI.NetQuoteWebsite.DBO.PendingApplications AS T 15 | INNER JOIN NETQUOTE.DBO.PendingApplications 16 | ON NETQUOTE.DBO.PendingApplications.APPLICATIONID = T.APPLICATIONID 17 | WHERE NETQUOTE.DBO.PendingApplications.APPLICATIONID = T.APPLICATIONID 18 | AND T.BrandId IS NOT NULL -------------------------------------------------------------------------------- /When Backup Restore Index Will Finish.sql: -------------------------------------------------------------------------------- 1 | SELECT r.[session_id], 2 | c.[client_net_address], 3 | s.[host_name], 4 | c.[connect_time], 5 | [request_start_time] = s.[last_request_start_time], 6 | [current_time] = CURRENT_TIMESTAMP, 7 | r.[percent_complete], 8 | [estimated_finish_time] = DATEADD (MILLISECOND,r.[estimated_completion_time],CURRENT_TIMESTAMP), 9 | current_command = SUBSTRING(t.[text],r.[statement_start_offset]/2,COALESCE(NULLIF(r.[statement_end_offset], -1)/2, 2147483647) ), 10 | module = COALESCE(QUOTENAME(OBJECT_SCHEMA_NAME(t.[objectid], t.[dbid])) + '.' + QUOTENAME(OBJECT_NAME(t.[objectid], t.[dbid])), '') 11 | FROM sys.dm_exec_requests AS r 12 | INNER JOIN sys.dm_exec_connections AS c 13 | ON r.[session_id] = c.[session_id] 14 | INNER JOIN sys.dm_exec_sessions AS s 15 | ON r.[session_id] = s.[session_id] 16 | CROSS APPLY sys.dm_exec_sql_text(r.[sql_handle]) AS t 17 | WHERE r.[percent_complete] <> 0; -------------------------------------------------------------------------------- /WhoIsActive_Query.sql: -------------------------------------------------------------------------------- 1 | ;WITH CTE_ROWS AS ( 2 | SELECT ROW_NUMBER () OVER(Partition by collection_time order by [dd hh:mm:ss.mss] desc) as RN, 3 | RowId, collection_time, [dd hh:mm:ss.mss], session_id, sql_text, login_name, wait_info, tran_log_writes, tempdb_current, blocking_session_id, writes, used_memory, status, tran_start_time, open_tran_count, percent_complete, host_name, program_name, start_time, login_time 4 | from dbo.WhoIsActive (nolock) 5 | where collection_time > '20161113 10:42' 6 | and collection_time < '20161113 12:13' 7 | ) 8 | SELECT * 9 | FROM CTE_ROWS 10 | WHERE RN <= 5 11 | ORDER BY collection_time DESC, RN 12 | -------------------------------------------------------------------------------- /XML Query Exist Method Sample.sql: -------------------------------------------------------------------------------- 1 | 2 | DECLARE @xmlSnippet XML 3 | DECLARE @id SMALLINT 4 | DECLARE @value VARCHAR(20) 5 | SET @xmlSnippet = 6 | 'SQL Server Ninja 7 | Oracle Ninja 8 | MySQL Ninja 9 | ' 10 | -- this is what we will look for 11 | SET @id = 2 12 | SET @value ='SQL Server Ninja' 13 | -- note exist() will return only either :-- 1 (true) or 0 (false) 14 | 15 | -- check if a node called ninjaElement exists-- at any level in the XML snippet 16 | SELECT @xmlSnippet.exist('//ninjaElement') 17 | 18 | -- check if a node called bar exists 19 | SELECT @xmlSnippet.exist('//bar') 20 | 21 | -- check if attribute id exists anywhere 22 | SELECT @xmlSnippet.exist('//@id') 23 | 24 | -- check if attribute id exists within a ninjaElement tag 25 | SELECT @xmlSnippet.exist('//ninjaElement[@id]') 26 | 27 | -- check if the id attribute equals to what we saved-- in the @id variable 28 | SELECT @xmlSnippet.exist('/ninjaElement[@id=sql:variable("@id")]') 29 | 30 | -- check if the node text equals to what-- we saved in the @value variable 31 | SELECT @xmlSnippet.exist('/ninjaElement1') 32 | 33 | -------------------------------------------------------------------------------- /XML Sample.sql: -------------------------------------------------------------------------------- 1 | declare @x xml 2 | set @x = (select top 1 Content from dbo.dupes) 3 | 4 | select @X RAW_XML 5 | --SQL 2000 CODE 6 | 7 | -- Initialize XML handle 8 | DECLARE @hdoc INT 9 | EXEC sp_xml_preparedocument @hdoc OUTPUT, @x 10 | 11 | --SQL 2005 CODE 12 | 13 | SELECT 14 | x.header.value('@VisitorSessionID[1]', 'varchar(50)') AS PARSED_XML 15 | --, x.header.value('Typex[1]', 'varchar(20)') AS Typex2 16 | FROM @x.nodes('//QuoteRequest') AS x(header) 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /_1_TransactionLog_Table_Create.sql: -------------------------------------------------------------------------------- 1 | USE [DBA] 2 | GO 3 | 4 | /****** Object: Table [dbo].[TransLogMonitor] Script Date: 12/19/2018 6:09:20 PM ******/ 5 | SET ANSI_NULLS ON 6 | GO 7 | 8 | SET QUOTED_IDENTIFIER ON 9 | GO 10 | 11 | IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TransLogMonitor]') AND type in (N'U')) 12 | BEGIN 13 | CREATE TABLE [dbo].[TransLogMonitor]( 14 | [LogID] [int] IDENTITY(1,1) NOT NULL, 15 | [LogDate] [datetime] NOT NULL, 16 | [DatabaseName] [varchar](100) NOT NULL, 17 | [LogSizeMB] [decimal](18, 2) NOT NULL, 18 | [LogSpaceUsed] [decimal](18, 2) NOT NULL, 19 | [Status] [int] NOT NULL, 20 | [VLF_count] [int] NULL, 21 | CONSTRAINT [PK_TransLogMonitor_LogID] PRIMARY KEY CLUSTERED 22 | ( 23 | [LogID] ASC 24 | )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 100, DATA_COMPRESSION = PAGE) ON [PRIMARY] 25 | ) ON [PRIMARY] 26 | END 27 | GO 28 | 29 | IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DF_TransLogMonitor_LogDate]') AND type = 'D') 30 | BEGIN 31 | ALTER TABLE [dbo].[TransLogMonitor] ADD CONSTRAINT [DF_TransLogMonitor_LogDate] DEFAULT (getdate()) FOR [LogDate] 32 | END 33 | GO -------------------------------------------------------------------------------- /_Admin_PLE_Collection_BackEndTable_Creation.sql: -------------------------------------------------------------------------------- 1 | USE [DBA] 2 | GO 3 | 4 | /****** Object: Table [dbo].[PLE] Script Date: 2/5/2018 4:29:02 PM ******/ 5 | SET ANSI_NULLS ON 6 | GO 7 | 8 | SET QUOTED_IDENTIFIER ON 9 | GO 10 | 11 | CREATE TABLE [dbo].[PLE]( 12 | [PleID] [bigint] IDENTITY(1,1) NOT NULL, 13 | [ServerName] [varchar](32) NOT NULL, 14 | [ObjectNamme] [varchar](32) NOT NULL, 15 | [NumaNode] [char](3) NOT NULL, 16 | [PageLifeExpectancy] [int] NOT NULL, 17 | [CreatedDate] [datetime] NOT NULL, 18 | CONSTRAINT [PK_dbo_PLE_PleID] PRIMARY KEY NONCLUSTERED 19 | ( 20 | [PleID] ASC 21 | )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 100, DATA_COMPRESSION = PAGE) ON [PRIMARY] 22 | ) ON [PRIMARY] 23 | GO 24 | 25 | ALTER TABLE [dbo].[PLE] ADD CONSTRAINT [DF_dbo_PLE_CreatedDate] DEFAULT (getdate()) FOR [CreatedDate] 26 | GO 27 | 28 | 29 | USE [DBA] 30 | GO 31 | 32 | /****** Object: Index [CIX_dbo_PLE_CreatedDate] Script Date: 2/5/2018 4:29:17 PM ******/ 33 | CREATE CLUSTERED INDEX [CIX_dbo_PLE_CreatedDate] ON [dbo].[PLE] 34 | ( 35 | [CreatedDate] ASC 36 | )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 100, DATA_COMPRESSION = PAGE) ON [PRIMARY] 37 | GO 38 | 39 | -------------------------------------------------------------------------------- /copy-ISNdbbackuptoContentShare.ps1: -------------------------------------------------------------------------------- 1 | Get-Childitem X:\Backups\UserDatabases\ISN_DB_Full*.bak | where {$_.CreationTime -gt (Get-Date).AddDays(-1) } | Copy-Item -Destination \\Content2\Backup -------------------------------------------------------------------------------- /del-oldbackups-SystemDbs.ps1: -------------------------------------------------------------------------------- 1 | 2 | $factor = $Args[0] 3 | 4 | $disks = get-psdrive X 5 | 6 | $cutoff = (Get-Date).AddDays(-$factor) 7 | 8 | $path = $disks.name + ":\Backups\SystemDatabases\" 9 | 10 | if ((Test-Path $path) -eq "True") 11 | { 12 | $count = (Get-ChildItem $path -include *.bak -Exclude *goldcopy*,*donotdelete* -recurse | 13 | ?{$_.LastWriteTime -lt $cutoff -and !$_.PSIsContainer -and $_.PSPath -notlike "*do_not_delete*"}).Count 14 | if ($count -eq $null) {$count = 0} 15 | 16 | Get-ChildItem $path -include *.bak -Exclude *goldcopy*,*donotdelete* -recurse | 17 | ?{$_.LastWriteTime -lt $cutoff -and !$_.PSIsContainer -and $_.PSPath -notlike "*do_not_delete*"} | 18 | Remove-Item 19 | Write-Host "There were" $count "db backup files deleted from" $path 20 | } 21 | 22 | -------------------------------------------------------------------------------- /del-oldbackups-UserDBBackupFiles.ps1: -------------------------------------------------------------------------------- 1 | 2 | $factor = $Args[0] 3 | 4 | $disks = get-psdrive X 5 | 6 | $cutoff = (Get-Date).AddDays(-$factor) 7 | 8 | $path = $disks.name + ":\Backups\UserDatabases\" 9 | 10 | if ((Test-Path $path) -eq "True") 11 | { 12 | $count = (Get-ChildItem $path -include *.bak -Exclude *goldcopy*,*donotdelete* -recurse | 13 | ?{$_.LastWriteTime -lt $cutoff -and !$_.PSIsContainer -and $_.PSPath -notlike "*do_not_delete*"}).Count 14 | if ($count -eq $null) {$count = 0} 15 | 16 | Get-ChildItem $path -include *.bak -Exclude *goldcopy*,*donotdelete* -recurse | 17 | ?{$_.LastWriteTime -lt $cutoff -and !$_.PSIsContainer -and $_.PSPath -notlike "*do_not_delete*"} | 18 | Remove-Item 19 | Write-Host "There were" $count "db backup files deleted from" $path 20 | } 21 | 22 | -------------------------------------------------------------------------------- /del-oldbackups-UserDBTlogs.ps1: -------------------------------------------------------------------------------- 1 | 2 | $factor = $Args[0] 3 | 4 | $disks = get-psdrive X 5 | 6 | $cutoff = (Get-Date).AddDays(-$factor) 7 | 8 | $path = $disks.name + ":\Backups\UserDatabases\" 9 | 10 | if ((Test-Path $path) -eq "True") 11 | { 12 | $count = (Get-ChildItem $path -include *.trn -Exclude *goldcopy*,*donotdelete* -recurse | 13 | ?{$_.LastWriteTime -lt $cutoff -and !$_.PSIsContainer -and $_.PSPath -notlike "*do_not_delete*"}).Count 14 | if ($count -eq $null) {$count = 0} 15 | 16 | Get-ChildItem $path -include *.trn -Exclude *goldcopy*,*donotdelete* -recurse | 17 | ?{$_.LastWriteTime -lt $cutoff -and !$_.PSIsContainer -and $_.PSPath -notlike "*do_not_delete*"} | 18 | Remove-Item 19 | Write-Host "There were" $count "backup files deleted from" $path 20 | } 21 | 22 | -------------------------------------------------------------------------------- /get-all-sql-databases.txt: -------------------------------------------------------------------------------- 1 | login-AzureRmSubscription -------------------------------------------------------------------------------- /get-all-sql-databases_in_subscription.txt: -------------------------------------------------------------------------------- 1 | get-azurermsubscription 2 | 3 | Select-AzureRmSubscription -Subscription d9da86e1-7cc1-406a-8492-501fffbc33fe 4 | 5 | Get-AzureRMSQLserver 6 | Get-AzureRMSQLserver | select ResourceGroupName, ServerName, FullyQualifiedDomainName, Location 7 | Get-AzureRMSQLserver | select ResourceGroupName, ServerName, Location 8 | 9 | Get-AzureRMSQLDatabase -ResourceGroupName rg-universityofmissouri -ServerName universityofmissouri-db-01 10 | 11 | Get-AzureRMSQLDatabase -ResourceGroupName rg-universityofmissouri -ServerName universityofmissouri-db-01 | Where-Object{$_.DatabaseName -ne 'master'} 12 | Get-AzureRMSQLDatabase -ResourceGroupName rg-universityofmissouri -ServerName universityofmissouri-db-01 | Where-Object{$_.DatabaseName -ne 'master'} | Select DatabaseName 13 | 14 | 15 | -------------------------------------------------------------------------------- /param.txt: -------------------------------------------------------------------------------- 1 | c:\testfile.dat 2 0x0 2048 2 | #I:\testfile.dat 2 0x0 20480 3 | #d:\testfile.dat 2 0x0 100 -------------------------------------------------------------------------------- /pr_ExecSQLCmd_Update_for_use_with_Stripes.sql: -------------------------------------------------------------------------------- 1 | USE [DBAdmin] 2 | GO 3 | drop procedure [pr_ExecSQLCmd] 4 | go 5 | /****** Object: StoredProcedure [dbo].[pr_ExecSQLCmd] Script Date: 6/17/2013 4:11:24 PM ******/ 6 | SET ANSI_NULLS ON 7 | GO 8 | 9 | SET QUOTED_IDENTIFIER OFF 10 | GO 11 | 12 | 13 | CREATE PROCEDURE [dbo].[pr_ExecSQLCmd] 14 | @SQLCmd VARCHAR(max), --NVARCHAR(2048), 15 | @Source VARCHAR(64), 16 | @rc INT = NULL OUTPUT 17 | AS 18 | 19 | IF @Source != 'pr_DatabaseBackup' 20 | BEGIN 21 | PRINT 'Invalid Source Routine - Code execution not allowed' 22 | SELECT @rc = -1 23 | RETURN 24 | END 25 | 26 | SELECT @rc = 0 27 | 28 | BEGIN TRY 29 | EXEC (@SQLCmd) 30 | END TRY 31 | BEGIN CATCH 32 | SELECT @rc = ERROR_NUMBER() 33 | END CATCH 34 | 35 | RETURN 36 | GO 37 | 38 | 39 | -------------------------------------------------------------------------------- /sp_DBPermissions.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/himadanreddy/SQL-DBA-SCRIPTS/3111841fe0efca6d018929c71d2201506912ddcb/sp_DBPermissions.sql -------------------------------------------------------------------------------- /sp_MSforeachdb_sample.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/himadanreddy/SQL-DBA-SCRIPTS/3111841fe0efca6d018929c71d2201506912ddcb/sp_MSforeachdb_sample.sql -------------------------------------------------------------------------------- /sp_SrvPermissions.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/himadanreddy/SQL-DBA-SCRIPTS/3111841fe0efca6d018929c71d2201506912ddcb/sp_SrvPermissions.sql -------------------------------------------------------------------------------- /sp_configure settings.sql: -------------------------------------------------------------------------------- 1 | EXEC sp_configure 'show advanced options',1 2 | GO 3 | RECONFIGURE 4 | GO 5 | EXEC sp_configure 'backup checksum default',1 6 | GO 7 | RECONFIGURE 8 | GO 9 | EXEC sp_configure 'backup compression default',1 10 | GO 11 | RECONFIGURE 12 | GO 13 | EXEC sp_configure 'cost threshold for parallelism',50 14 | GO 15 | RECONFIGURE 16 | GO 17 | EXEC sp_configure 'Database Mail XPs',1 18 | GO 19 | RECONFIGURE 20 | GO 21 | EXEC sp_configure 'max server memory (MB)',51200 -- 50GB x 1024 22 | GO 23 | RECONFIGURE 24 | GO 25 | EXEC sp_configure 'min server memory (MB)',51200 -- 50GB x 1024 26 | GO 27 | RECONFIGURE 28 | GO 29 | EXEC sp_configure 'optimize for ad hoc workloads',1 30 | GO 31 | RECONFIGURE 32 | GO 33 | EXEC sp_configure 'remote admin connections',1 34 | GO 35 | RECONFIGURE 36 | GO 37 | EXEC sp_configure 38 | -------------------------------------------------------------------------------- /sp_update_job_for_non_admins_execution.sql: -------------------------------------------------------------------------------- 1 | USE msdb 2 | GO 3 | EXEC dbo.sp_update_job_for_non_admins 4 | @job_name = N'ZZZ_Test_Job' -- the job name 5 | , @owner_login_name = 'SSBINFO\gholder' -- new owner in SSBINFO domain 6 | , @enabled = 1 ; -- 1 enable / 0 disable job 7 | GO -------------------------------------------------------------------------------- /sp_whoisactive_column_list_return.sql: -------------------------------------------------------------------------------- 1 | use master 2 | go 3 | exec sp_WhoIsActive @get_outer_command = 1, 4 | @output_column_list = '[dd%],[session_id],[blocking%],[sql_text],[sql_command],[login_name],[wait_info],[host_name],[database_name],[program_name],[tran_log%],[cpu%],[temp%],[block%],[reads%],[writes%],[context%],[physical%],[start%]' 5 | -------------------------------------------------------------------------------- /sqlio.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/himadanreddy/SQL-DBA-SCRIPTS/3111841fe0efca6d018929c71d2201506912ddcb/sqlio.exe -------------------------------------------------------------------------------- /sys2.buffer_cache_usage.sql: -------------------------------------------------------------------------------- 1 | ------------------------------------------------------------------------ 2 | -- Script: sys2.buffer_cache_usage.sql 3 | -- Version: 1 4 | -- Release Date: 2011-03-04 5 | -- Author: Davide Mauri (Solid Quality Mentors) 6 | -- Credits: - 7 | -- License: Microsoft Public License (Ms-PL) 8 | -- Target Version: SQL Server 2005 RTM or above 9 | -- Tab/indent size: 4 10 | -- Usage: SELECT * FROM sys2.plan_cache_size 11 | -- Notes: Show how much memory is being used for Plan Cache 12 | ------------------------------------------------------------------------ 13 | 14 | IF NOT EXISTS(SELECT * FROM sys.schemas s WHERE s.[name] = 'sys2') 15 | EXEC sp_executesql N'CREATE SCHEMA sys2' 16 | go 17 | 18 | IF (OBJECT_ID('sys2.buffer_cache_usage', 'V') IS NOT NULL) 19 | DROP VIEW sys2.buffer_cache_usage 20 | GO 21 | 22 | CREATE VIEW sys2.buffer_cache_usage 23 | as 24 | with cte as 25 | ( 26 | select 27 | database_id, 28 | (count(*) * 8) / 1024. as cache_memory_usage_in_mb 29 | from 30 | sys.dm_os_buffer_descriptors with (nolock) 31 | group by 32 | database_id 33 | ) 34 | select 35 | database_name = d.name, 36 | cache_memory_usage_in_mb 37 | from 38 | cte c 39 | inner join 40 | sys.databases d on c.database_id = d.database_id 41 | -------------------------------------------------------------------------------- /sys2.query_memory_grants (1).sql: -------------------------------------------------------------------------------- 1 | ------------------------------------------------------------------------ 2 | -- Script: sys2.query_memory_grants.sql 3 | -- Version: 1.0 4 | -- Release Date: 2010-10-15 5 | -- Author: Davide Mauri (Solid Quality Mentors) 6 | -- Credits: - 7 | -- License: Microsoft Public License (Ms-PL) 8 | -- Target Version: SQL Server 2005 RTM or above 9 | -- Tab/indent size: 4 10 | -- Usage: SELECT * FROM sys2.query_memory_grants() 11 | -- Notes: Wrapper around sys.dm_exec_query_memory_grants. If @include_plan = 1 also gather query plans 12 | -- WARNING: On a highly used system can be time consuming! 13 | ------------------------------------------------------------------------ 14 | 15 | IF NOT EXISTS(SELECT * FROM sys.schemas s WHERE s.[name] = 'sys2') 16 | EXEC sp_executesql N'CREATE SCHEMA sys2' 17 | go 18 | 19 | IF (OBJECT_ID('sys2.query_memory_grants', 'IF') IS NOT NULL) 20 | DROP FUNCTION sys2.query_memory_grants 21 | GO 22 | 23 | CREATE FUNCTION sys2.query_memory_grants(@include_plan BIT = 0) 24 | RETURNS TABLE 25 | AS 26 | RETURN 27 | SELECT 28 | database_id = st.dbid, 29 | [object_id] = st.objectid, 30 | query_text = st.[text], 31 | qp.query_plan, 32 | object_type = cp.objtype, 33 | cache_object_type = cp.cacheobjtype, 34 | qg.* 35 | FROM 36 | sys.dm_exec_query_memory_grants qg 37 | LEFT JOIN 38 | sys.dm_exec_cached_plans cp on qg.[plan_handle] = cp.[plan_handle] 39 | OUTER APPLY 40 | sys.dm_exec_sql_text([sql_handle]) st 41 | OUTER APPLY 42 | sys.dm_exec_query_plan(CASE WHEN @include_plan = 1 THEN qg.[plan_handle] ELSE null END) qp 43 | 44 | GO 45 | -------------------------------------------------------------------------------- /sys2.query_memory_grants.sql: -------------------------------------------------------------------------------- 1 | ------------------------------------------------------------------------ 2 | -- Script: sys2.query_memory_grants.sql 3 | -- Version: 1.0 4 | -- Release Date: 2010-10-15 5 | -- Author: Davide Mauri (Solid Quality Mentors) 6 | -- Credits: - 7 | -- License: Microsoft Public License (Ms-PL) 8 | -- Target Version: SQL Server 2005 RTM or above 9 | -- Tab/indent size: 4 10 | -- Usage: SELECT * FROM sys2.query_memory_grants() 11 | -- Notes: Wrapper around sys.dm_exec_query_memory_grants. If @include_plan = 1 also gather query plans 12 | -- WARNING: On a highly used system can be time consuming! 13 | ------------------------------------------------------------------------ 14 | 15 | IF NOT EXISTS(SELECT * FROM sys.schemas s WHERE s.[name] = 'sys2') 16 | EXEC sp_executesql N'CREATE SCHEMA sys2' 17 | go 18 | 19 | IF (OBJECT_ID('sys2.query_memory_grants', 'IF') IS NOT NULL) 20 | DROP FUNCTION sys2.query_memory_grants 21 | GO 22 | 23 | CREATE FUNCTION sys2.query_memory_grants(@include_plan BIT = 0) 24 | RETURNS TABLE 25 | AS 26 | RETURN 27 | SELECT 28 | database_id = st.dbid, 29 | [object_id] = st.objectid, 30 | query_text = st.[text], 31 | qp.query_plan, 32 | object_type = cp.objtype, 33 | cache_object_type = cp.cacheobjtype, 34 | qg.* 35 | FROM 36 | sys.dm_exec_query_memory_grants qg 37 | LEFT JOIN 38 | sys.dm_exec_cached_plans cp on qg.[plan_handle] = cp.[plan_handle] 39 | OUTER APPLY 40 | sys.dm_exec_sql_text([sql_handle]) st 41 | OUTER APPLY 42 | sys.dm_exec_query_plan(CASE WHEN @include_plan = 1 THEN qg.[plan_handle] ELSE null END) qp 43 | 44 | GO 45 | --------------------------------------------------------------------------------