├── .gitignore ├── ADS └── README.md ├── Articles ├── Backup │ ├── How to Build a SQL Server Disaster Recovery Plan with Google Compute Engine.pdf │ ├── Optimizing Your Query Plans with the SQL Server 2014 Cardinality Estimator.docx │ ├── Permissions_Poster_SQL_Server_2008_R2.pdf │ ├── Permissions_Poster_SQL_Server_2012.pdf │ ├── Permissions_Poster_SQL_Server_2014.pdf │ ├── Permissions_Poster_SQL_Server_2016_and_SQLDB.pdf │ ├── Permissions_Poster_SQL_Server_vNext_and_SQLDB.pdf │ ├── SQL Server Performance Tuning in Google Compute Engine.pdf │ ├── The Curse and Blessings of Dynamic SQL.htm │ ├── To BLOB or Not To BLOB Large Object Storage in a Database or a Filesystem.pdf │ └── sql server on vmware best practices guide.pdf └── README.md ├── CLR ├── README.md ├── Regex │ ├── Fill_Factor │ │ ├── InstallRegex.sql │ │ ├── RegexSQLCLR.vb │ │ ├── installRegexAssembly.sql │ │ └── installRegexSample.sql │ └── SqlRegularExpressions_SQLServerProject_QuickDeployment.zip ├── SplitStrings_CLR.cs └── SplitterB_CLR.sql ├── CONTRIBUTING.md ├── Errors ├── Backup │ ├── Be aware of 701 error if you use memory optimized table variable in a loop.maff │ ├── CREATE DATABASE – I’ve not seen that before..maff │ ├── Case study Troubleshooting Doomed Transactions.maff │ ├── Compressed backup errors and TF 3042.maff │ ├── Nuance of datetime data type in SQL Server.maff │ ├── SQL SERVER - Disabling 15000 Partitions (15k).maff │ ├── SQL SERVER - FIX Error Msg 8672 - The MERGE Statement Attempted to UPDATE or DELETE the Same Row More Than Once.maff │ ├── SQL SERVER - FIX Error 913, Severity 16 - Could Not Find Database ID 3. Database May Not be Activated Yet or May be in Transition.maff │ ├── SQL SERVER - Logon Failure The User has not Been Granted the Requested Logon Type at This Computer.maff │ ├── SQL Server 2016 Online ALTER COLUMN Operation.maff │ ├── Unable to restore a backup – Msg 3241.maff │ └── Who owns your availability groups.maff ├── Identity_gap_sql_server_2012.sql ├── PDB │ ├── README.md │ ├── SQL-Server-2008-R2.md │ ├── SQL-Server-2008.md │ ├── SQL-Server-2012.md │ ├── SQL-Server-2014.md │ ├── SQL-Server-2016.md │ ├── SQL-Server-2017.md │ └── SQL-Server-2019.md ├── README.md └── regedit_sqlserver.png ├── Extended_Events ├── ADS_Standard_Azure.sql ├── APC_Reverted_plan_corrections.sql ├── APC_plans_that_are_not_corrected.sql ├── AppExecutionTimeout.sql ├── AuditFileSize.sql ├── AutoTuneMonitor.sql ├── BackupRestoreTrace.sql ├── CheckpointTracking.sql ├── ConfigurationItemsChanged.sql ├── ConvertingSQLTracetoExtendedEvents.sql ├── DBRecoveryProgress.sql ├── DarkQueries.sql ├── Deadlocks.sql ├── FileSizeChanges.sql ├── ImplicitConversionOnly.sql ├── InvestigateWaits.sql ├── InvestigateWaitsMaxDop.sql ├── LinkedServerMonitor.sql ├── LockEscalation.sql ├── LoginFailure.sql ├── MonitorPageSplits.sql ├── ProcedureWaits.sql ├── QueryExecutionDetails.sql ├── README.md ├── Recompile_Histogram.sql ├── SchemaQueryByUser.sql ├── System_Health_Addition.sql ├── TrackApiCursor.sql ├── TrackDBFileChange.sql ├── TrackPageSplits.sql ├── TrackTFChange.sql ├── XE_Truncate.sql ├── system_health.sql └── system_health_azure.sql ├── Help └── README.md ├── LICENSE ├── PowerShell ├── Add-UserToRole.ps1 ├── Clone-SQLLogin.ps1 ├── Collect_Windows_Counters.ps1 ├── Compare-Server-Settings.ps1 ├── Convert-LSN.ps1 ├── Convert_trc_to_2008r2.ps1 ├── Create-Deploy-SQL-Script.ps1 ├── CsvSqlimport.ps1 ├── Disable_CEIP.ps1 ├── Disable_Enable_All_Triggers_In_Database.ps1 ├── Export-AllPlans.ps1 ├── Export-SQLTableToCSV.ps1 ├── Export_Query_To_Csv.ps1 ├── Fast_table_to_csv.ps1 ├── Format-SQLCode.ps1 ├── Get-CmsHosts.ps1 ├── Get-MachineInformationExcel.ps1 ├── Get-QueryPlan.ps1 ├── Get-SQLErrorLog.ps1 ├── Get-SQLServerGlobalTraceFlags.ps1 ├── Get-SQLServerSecurityReview.ps1 ├── Get-SQLUnattendedFile.ps1 ├── Get-SystemInfo.ps1 ├── Get-Windows-Block-Size.ps1 ├── Get-port-information-for-SQL-Server-instances.ps1 ├── Multiply_SQL_Server_Connections.ps1 ├── OnlineFilegroupMigration.ps1 ├── ParameterCaseCheck.ps1 ├── Parse-TSQL.ps1 ├── README.md ├── Read-XEL-File.ps1 ├── Read_XEL_file.ps1 ├── ResetSqlSaPassword.psm1 ├── SQL_Server_Discovery_Report.ps1 ├── SQL_Server_Test_backups.ps1 ├── SQL_Server_linked_server_connection_check.ps1 ├── SQL_Server_table_to_csv.ps1 ├── Scripting_Out_SQL_Server_Data_As_Insert_Statements.ps1 ├── Send-SqlDataToExcel.ps1 ├── Set_Extended_Events_Sessions_to_AutoStart.ps1 ├── Shred-XElogs.ps1 ├── Simulate_Databse_Load.ps1 ├── Test-SQLScripts.ps1 ├── Truncate-AllTables.ps1 ├── WOX_Permissions.ps1 └── When-SQL-Serve-was-Rebooted.ps1 ├── README.md ├── SQL Server DBCC List.md ├── SQL Server Data Types.md ├── SQL Server Drivers.md ├── SQL Server Edition.md ├── SQL Server Hints.md ├── SQL Server Licensing.md ├── SQL Server Name Convention and T-SQL Programming Style.md ├── SQL Server People.md ├── SQL Server Trace Flag.md ├── SQL Server Version.md ├── SSMS ├── README.md ├── SSMS_Addins.md ├── SSMS_Errors.md ├── SSMS_Shortcuts.md ├── SSMS_Snippets │ ├── Count Rows Per Partition.snippet │ ├── Count Rows.snippet │ ├── Create Numbers Table.snippet │ ├── Dbcc InputBuffer.snippet │ ├── Index Fragmentation.snippet │ ├── Index Usage.snippet │ ├── Objects Containing String.snippet │ ├── Procedure_dynamic_create.sql │ ├── SP_HelpIndex.snippet │ ├── Show Current Locks.snippet │ ├── Show Current Running Queries.snippet │ └── loop.sql ├── SSMS_Tips.md ├── SSMS_Tips │ ├── 05_ALT+Arrow.gif │ ├── 05_ALT+PASTE.gif │ ├── 24_SSMS_command-line_parameters.png │ ├── 24_changing_what_ssms_opens_on_startup.gif │ ├── 24_changing_what_ssms_opens_on_startup_nosplash.png │ ├── 24_create_solution_commonly_used_sql_scripts.gif │ ├── 25_query_execution_options.png │ ├── 25_query_execution_options_ansi.png │ ├── 26_sql_server_diagnostics_extension.png │ ├── 28_connect_to_sql_servers_in_another_domain_using_windows_authentication_with_credential.gif │ ├── 28_connect_to_sql_servers_in_another_domain_using_windows_authentication_with_shortcut.gif │ ├── 29_SSMS_Database_Default_Reports.png │ ├── 29_SSMS_Server_Default_Reports.png │ ├── 32_object_explore_details_01.png │ ├── 32_object_explore_details_02.png │ ├── 32_object_explore_details_03.png │ ├── 38_using_ssms_with_powerbi_01.jpg │ ├── 38_using_ssms_with_powerbi_02.jpg │ ├── AutoRecover_in_SSMS.png │ ├── README.md │ ├── SQL_Vulnerability_Assessment.gif │ ├── additional_connection_parameters.png │ ├── disable_copy_of_empty_text.png │ ├── import_and_export_settings.png │ ├── keyboard_shortcuts_for_stored_procedures.png │ ├── splitting_the_query_window.gif │ ├── ssms_script_objects.gif │ ├── ssms_script_objects_server_version.png │ ├── undock_tabs_and_windows_for_multi_monitor_support.gif │ └── working_with_tabs_headers.png └── SSMS_vssettings │ ├── AB.DarkScheme.LargeFonts.vssettings │ ├── AB.DarkScheme.NormalFonts.vssettings │ ├── NewSettings_17.2(14.0.17177).vssettings │ ├── NewSettings_2014(12.0.5556).vssettings │ ├── NewSettings_Default_17.2(14.0.17177).vssettings │ ├── NewSettings_Default_18.7.1(15.0.18358).vssettings │ ├── NewSettings_Default_2014(12.0.5556).vssettings │ ├── README.md │ └── ktaranov_18.7.1.vssettings ├── Sample_Databases ├── Create_Enlarged_Adventureworks_Tables.sql ├── Database_script.sql ├── Oracle_Employee_Database.sql ├── PerformanceV3.sql ├── README.md └── TSQLV4.sql ├── Scripts ├── Adding_Trace_Flags_To_Startup_Parameters.sql ├── AutoGuessingForeignKeyConstraints.sql ├── Auto_Generate_Database_Documentation.sql ├── Azure SQL Database Diagnostic Information Queries.sql ├── Backup_Restore_What’s_My_Status.sql ├── Bad_Query_Example_13_JOINS.sql ├── Benchmark_TSQL.R ├── Blocked_Session.sql ├── Bufer_Cache_Info.sql ├── BufferPoolExtension.sql ├── Build_CREATE_TABLE_statement_using_dm_exec_describe_first_result_set.sql ├── CPU_Utilization.sql ├── CPU_Utilization_Graphical_form.sql ├── Cached_Data_Per_Object_in_Memory.sql ├── Change_NonDefault_Collation_for_all_tables.sql ├── CheckSpectreMeltdownStatus.sql ├── Check_Reserved_Words_For_Object_Names.sql ├── Checking_Your_Backup_Paths_Exist_and_Automatically_Create_it.sql ├── Checkpoint_XE.sql ├── Code_Reuse_With_Dynamic_SQL_and_Temp_Procedures_Example.sql ├── Compare_2_tables_by_column_names.sql ├── Compress_Tables_And_Indexes.sql ├── Configure_SQL_Agent_Alerts.sql ├── Count character matches.sql ├── Count_Database_Reads_and_Writes.sql ├── Create_2_Million_Tables.sql ├── Create_JOIN_Query_Between_Multiple_Tables_Dynamically.sql ├── Current_Running_Queries.sql ├── Current_Running_Tasks_and_Server_Info.sql ├── DBCC_CHECKDB_Latest_date.sql ├── Data_Dictionary_Information.sql ├── Database_Mail_Configuration.sql ├── Database_Mail_Problems.sql ├── Databases_Report.sql ├── Date_Calendar_Cross-Reference_Table.sql ├── Date_Format_Cheat_Sheet.sql ├── Decrypt T-SQL module.sql ├── Delete_Login_And_All_Users.sql ├── DetermineSpaceWithinSQLDatabaseFiles.sql ├── Disable_Enable_All_Triggers_In_Database.sql ├── Disabling_Jobs_Schedules.sql ├── Drop_all_objects_in_schema.sql ├── Dynamic_GRANT_Generation.sql ├── DynamicallyGenerateDMAStatement.sql ├── Enable Microsoft.ACE.OLEDB.12.0.sql ├── Enabling_Jobs_Schedules.sql ├── Estimate_When_Long_Running_SQL_Processes_Will_Finish.sql ├── Extract_Scale_Part_From_Decimal_Number.sql ├── Failed_SQL_Server_Agent_Jobs_With_Restart_Command.sql ├── Fast_alternative_to_sp_WhoIsActive.sql ├── FindDBConnectionLeaks.sql ├── FindLongRunningJobSteps.sql ├── FindTablesWithSimilarTableStructure.sql ├── Find_Foreign_Key_Chains_For_Tables.sql ├── Find_Maximum_Float_Values.sql ├── Find_Non_Sargable_Queries.sql ├── Find_Not_Used_Legacy_Tables.sql ├── Find_Object_Dependecy.sql ├── Find_SQL_Server_Integer_Columns_to_Make_Skinnier.sql ├── Find_Status_of_SQL_Server_Statistics.sql ├── Find_Synonyms_for_nested_objects_in_the_different_databases.sql ├── Find_Synonyms_for_nested_objects_in_the_same_database.sql ├── Find_Weak_Passwords.sql ├── Find_and_fix_that_troublesome_Windows_Power_setting.sql ├── FindingImplicitColumnConversionsInPlanCache.sql ├── FindingSpecificColumns.sql ├── Finding_Blocking_Queries.sql ├── Finding_Host_Names_for_Failed_login_attempts.sql ├── Fix_The_Broken_Dependencies_On_All_Objects.sql ├── Foreign_Key_batch_rename.sql ├── Foreign_Keys_With_No_Index.sql ├── GenerateTSQLTimeSlices.sql ├── Generate_BIML_Script.sql ├── Generate_Restore_Script_From_Backup_Folder.sql ├── Generate_table_definition_to_match_query.sql ├── GetResourceNameFromBlockedProcessReport.sql ├── Get_Amazon_RDS_Instance_Size.sql ├── Get_CPU_Usage_Per_Database.sql ├── Get_Coulmn_Statistics_By_Name.sql ├── Get_Create_or_Alter_Index_Progress.sql ├── Get_Database_Size_With_Graph.sql ├── Get_Identity_Column_Information.sql ├── Get_Latest_Success_and_Failure_Login.sql ├── Get_Opened_Transactions_Info.sql ├── Get_SQLServer_Startup_Parameters.sql ├── Get_SQL_Server_Agent_Information.sql ├── Get_SQL_Server_Backup_Directory.sql ├── Get_SQL_Server_NUMA_Memory.sql ├── Get_Statistics_Details.sql ├── Get_Table_Hierarchy.sql ├── Get_Table_and_Index_Storage_Size.sql ├── Get_latches_Objects.sql ├── GoogleJobTimeline.sql ├── How_much_will_it_cost_or_save_to_rebuild_that_index.sql ├── How_old_your_backups.sql ├── How_to_Find_Queries_Using_an_Index.sql ├── How_to_obtain_the_deadlocks_on_Azure.sql ├── IN_Memory_Example_2014.sql ├── IN_Memory_Example_2017.sql ├── IdentifyObjectNameForCreateAndAlterUsingFn_dblog.sql ├── Identify_All_Logins_With_No_Associated_Default_Database_User.sql ├── Identifying_In-Memory_Objects_When_Querying_the_Transaction_Log.sql ├── Index Breakdown.sql ├── Index_Creating_Info.sql ├── Indexes_Script_Out.sql ├── Job_AG_Failover_Detected.sql ├── Job_AG_Resume_Data_Movement.sql ├── Jobs_Detailed_History.sql ├── Jobs_Find_And_Replace_Text.sql ├── Jobs_Get_Runing_info.sql ├── LatchStats.sql ├── Line_Of_Codes_In_database.sql ├── Listing_SQL_Agent_Jobs_Running_at_a_Specific_Time.sql ├── MAXDOP_recommendation.sql ├── MaxDop_2016_and_higher.sql ├── MaxServerMemoryCalculator.sql ├── Memory_Consumption_By_Object.sql ├── MisleadingSQLServerPerformanceCounters.sql ├── Monitor_Deadlocks_with_Extended_Events.sql ├── Move_tempdb.sql ├── New_Default_Database_Assignment_For_Any_Login_Missing_Their_Default_Database.sql ├── Numbers_DATALENGTH.sql ├── Objects_Size_In_Database.sql ├── Overview_HADR_AlwaysOn_Local_Replica_Server.sql ├── PIVOT_Columns_generator.sql ├── Partial_Restore_Demo.sql ├── Pattern_Match.sql ├── PowerSavingCheck.sql ├── Queries_vulnerable_to_SQL_injection.sql ├── Queries_with_parallelism.sql ├── QueryActiveDirectory.sql ├── Query_Store_Export.sql ├── README.md ├── Read_Default_Trace.sql ├── Read_Error_Log_File.sql ├── Read_errorlog.sql ├── Remove_Leading_and_Trailing_Backward_and_Forward_Slashes.sql ├── RenameDefaultConstraints.sql ├── Reseed_Identity_Column_Value_To_Last_Value.sql ├── Restore_Database_Dynamic_SQL.sql ├── Restore_script_for_Ola_Hallengren_backup.sql ├── Ring_Bufer_Analyze.sql ├── Run_scripts.bat ├── SQL Managed Instance Diagnostic Information Queries.sql ├── SQL Server 2005 Diagnostic Information Queries.sql ├── SQL Server 2008 Diagnostic Information Queries.sql ├── SQL Server 2008 R2 Diagnostic Information Queries.sql ├── SQL Server 2012 Diagnostic Information Queries.sql ├── SQL Server 2014 Diagnostic Information Queries.sql ├── SQL Server 2016 Diagnostic Information Queries.sql ├── SQL Server 2016 SP1 Diagnostic Information Queries.sql ├── SQL Server 2016 SP2 Diagnostic Information Queries.sql ├── SQL Server 2017 Diagnostic Information Queries.sql ├── SQL Server 2019 Diagnostic Information Queries.sql ├── SQLServer_Memory_Information.sql ├── SQL_Azure_Approximate_Datetime_Restart.sql ├── SQL_Server_Defaults.sql ├── SQL_Server_Fixed_Role_Permissions.sql ├── Save_Error_Log_To_Table.sql ├── Search_Script.sql ├── Security_Audit_Report.sql ├── Selects_That_Cause_Writes.sql ├── Server_Parameters.sql ├── Show all permissions in a database.sql ├── ShredDeadlockGraph.sql ├── ShredDeadlockGraph_Sample1.xml ├── ShredDeadlockGraph_Sample2.xml ├── Shredding_XML_Data_From_Extended_Events.sql ├── Simulate_Permissions_Logins_Change.sql ├── Simulate_SQL_Server_Users_Hack.sql ├── Sort_SQL_Server_Tables_into_similarly_sized_buckets.sql ├── Sort_UID_Demo.sql ├── Space used by object.sql ├── SpaceusedByTable.sql ├── SplitFileGroup.sql ├── Stop_long-running_SQL_Server_Agent_Jobs.sql ├── Suspect_Database_Pages.sql ├── Table_Count_Fast_Alternatives.sql ├── Table_Parameters.sql ├── Tempdb_Contention.sql ├── Temporal_Table_Maker.sql ├── Test_job.sql ├── Trace_Flag │ ├── Trace_Flag_1165.sql │ ├── Trace_Flag_2371.sql │ ├── Trace_Flag_3895.sql │ ├── Trace_Flag_460.sql │ ├── Trace_Flag_8602.sql │ ├── Trace_Flag_8726.sql │ └── Trace_Flag_8727.sql ├── Truncate log file.sql ├── TuneYourIndexingStrategyWithDMVs.sql ├── UnPivot_Output_Restore_Headeronly.sql ├── Uppercase_All_String_Columns.sql ├── Using_OPENROWSET_to_Query_Excel.sql ├── VLF_Info.sql ├── Visualizing_Agent_Jobs_in_SSMS.sql ├── Visualizing_VLF.sql ├── Wait_Statistics.sql ├── Wait_Statistics_Snapshot.sql ├── What_Agent_Job_is_Running.sql ├── When_SQL_Server_Was_Installed.sql ├── Which_Filegroup_is_that_Partition_Using.sql ├── Which_Indexes_are_not_Used.sql ├── Which_databases_were_backed_up_and_when.sql ├── Which_sp_configure_Options_Clear_the_Plan_Cache.sql ├── WhiteListIPTable.sql ├── Who_dropped_altered_database_object.sql ├── Who_dropped_database.sql ├── Windows logins not in AD.sql ├── glen_berry_diagnostic_queries_links.txt ├── mssql2csv.R ├── tempdb_Information.sql └── tempdb_usage.sql ├── Solution ├── BaselineCollector │ ├── BaselineCollectorSolution.sql │ └── README.md ├── Ola_Maintenance_Solution │ ├── CommandExecute.sql │ ├── CommandLog.sql │ ├── DatabaseBackup.sql │ ├── DatabaseIntegrityCheck.sql │ ├── IndexOptimize.sql │ ├── MaintenanceSolution.sql │ └── README.md ├── README.md ├── SysJobHistory │ ├── DBA_sp_jobhistory_row_limiter.sql │ ├── DBA_sysjobhistory_config_tbl.sql │ ├── DBA_sysjobhistory_driver.sql │ ├── DBA_sysjobhistory_driver_Tests.sql │ ├── README.md │ └── seeddata.sql └── dbWarden │ ├── README.md │ ├── dbWarden.sql │ └── dbWarden_UNINSTALL.sql ├── Stored_Procedure ├── README.md ├── Recover_Deleted_Data_Proc.sql ├── dbo.PerformanceGraph.sql ├── dbo.sp_AllocationMetadata.sql ├── dbo.sp_BenchmarkTSQL.sql ├── dbo.sp_BlitzInMemoryOLTP.sql ├── dbo.sp_Blocked_Process_Report_Viewer.sql ├── dbo.sp_ChangeDatabaseOwnerShip.sql ├── dbo.sp_DBA_job_notification.sql ├── dbo.sp_Defrag_Indexes.sql ├── dbo.sp_Depends.sql ├── dbo.sp_DropIndexes.sql ├── dbo.sp_Example_RegisterAssembly_PDFCLR.sql ├── dbo.sp_FailedJobs.sql ├── dbo.sp_FailedLogins.sql ├── dbo.sp_GenerateMerge.sql ├── dbo.sp_IndexAnalysis-v11.sql ├── dbo.sp_PerfSQ.sql ├── dbo.sp_PrintString.sql ├── dbo.sp_RestoreGene.sql ├── dbo.sp_RestoreScript.sql ├── dbo.sp_SQLskills_ExposeColsInIndexLevels.sql ├── dbo.sp_SQLskills_helpindex.sql ├── dbo.sp_Snapshot.sql ├── dbo.sp_WhatsupQueryStore.sql ├── dbo.sp_capture_login_auth.sql ├── dbo.sp_ctrl3.sql ├── dbo.sp_doc.sql ├── dbo.sp_estindex.sql ├── dbo.sp_foreign_key$batch_drop_and_recreate.sql ├── dbo.sp_generate_merge.sql ├── dbo.sp_helpExpandView.sql ├── dbo.sp_help_permissions.sql ├── dbo.sp_helpme.sql ├── dbo.sp_ns_shrink_db_log.sql ├── dbo.sp_sizeoptimiser.sql ├── dbo.sp_sizing.sql ├── dbo.sp_sqltrace.sql ├── dbo.sqlg_ParseDiskskpXml.sql ├── dbo.udp_IntegerListfromRanges.sql ├── dbo.usp_Breadth_First.sql ├── dbo.usp_BulkUpload.sql ├── dbo.usp_CopyLogins.sql ├── dbo.usp_CreatePlantUMLCode.sql ├── dbo.usp_DBA_Rename_Database.sql ├── dbo.usp_Dijkstra.sql ├── dbo.usp_EnableAndAddFileStreamForDatabase.sql ├── dbo.usp_FindDbObjects.sql ├── dbo.usp_GenerateRandomPassword.sql ├── dbo.usp_Generate_Merge.sql ├── dbo.usp_GetPackageDetails.sql ├── dbo.usp_GetUntrustedForeignKeys.sql ├── dbo.usp_Kruskal.sql ├── dbo.usp_LoadTableBlobs.sql ├── dbo.usp_LogError.sql ├── dbo.usp_Object_Search.sql ├── dbo.usp_Prim.sql ├── dbo.usp_PrintDebug.sql ├── dbo.usp_PrintError.sql ├── dbo.usp_RandomWait.sql ├── dbo.usp_RunCheckAllUntrustedForeignKeys.sql ├── dbo.usp_SQL_Server_System_Report.sql ├── dbo.usp_SQLskillsAnalyzeLog.sql ├── dbo.usp_SSIS_ScriptEnvironment.sql ├── dbo.usp_SearchOnAllDB.sql ├── dbo.usp_SearchStoredProcedureText.sql ├── dbo.usp_SetFileGrowth.sql ├── dbo.usp_String_Search.sql ├── dbo.usp_TableUnpivot.sql ├── dbo.usp_TopologicalSort.sql ├── dbo.usp_TransliterationEN2RU.sql ├── dbo.usp_UnusedInputParameters.sql ├── dbo.usp_bcpTableUnload.sql ├── dbo.usp_bcpTableUnloadBatchMode.sql ├── dbo.usp_bcpUnloadSelect.sql ├── dbo.usp_checkAllDatabases.sql ├── dbo.usp_generateIdentifier.sql └── dbo.usp_who5.sql ├── User_Defined_Function ├── FN_SPLIT.sql ├── README.md ├── dbo.ConvertHexLSN.sql ├── dbo.udf_InitCap.sql ├── dbo.udf_LCS.sql ├── dbo.udf_ListAllUnicodeCodePoints.sql ├── dbo.udf_LongestCommonSubstring.sql ├── dbo.udf_SeeAccessControlChanges.sql ├── dbo.udf_SeeDatabaseObjectChanges.sql ├── dbo.udf_StringComparisonsLevenshteinFullMatrix.sql ├── fnWordDifference.sql ├── fn_recurringDates.sql ├── udf_2DateDiff.sql ├── udf_AlphaNumericOnly.sql ├── udf_AlphaOnly.sql ├── udf_CalcWorkingHours.sql ├── udf_CalculateDistanceBetween2Coordinates.sql ├── udf_CheckDynamicSQL.sql ├── udf_ConvertRangesInIntegerList.sql ├── udf_DamLev.sql ├── udf_DateFormattedByMask.sql ├── udf_DigitsOnlyEE.sql ├── udf_FindPosition.sql ├── udf_ForeignKeyScript.sql ├── udf_FuzzySearchOf.sql ├── udf_GetNumsAB.sql ├── udf_GetResourceName.sql ├── udf_Haversine.sql ├── udf_INSTR.sql ├── udf_IntegerListFromRangesFunction.sql ├── udf_Is16digitValidCard.sql ├── udf_IsValidCard.sql ├── udf_JSONHierarchy.sql ├── udf_ParseFilePath.sql ├── udf_PatExclude8K.sql ├── udf_PatReplace8K.sql ├── udf_PatternSplitLoop.sql ├── udf_QueriesWithParameterizationProblems.sql ├── udf_RTF2Text.sql ├── udf_RemoveNonAlphaCharacters.sql ├── udf_RenderXMLToString.sql ├── udf_SecondConvertRangesInIntegerList.sql ├── udf_SplitStringByDelimiter.sql ├── udf_StringComparisonsLevenshteinString-based.sql ├── udf_StringComparisonsLongestCommonSubsequence.sql ├── udf_StringComparisonsMetaphoneAlgorithm.sql ├── udf_Tally.sql ├── udf_parseJSON.sql ├── udf_strtok.sql └── ufn_HolidayList.sql ├── Utilities ├── README.md └── SSMS_Alternatives.md └── img └── microsoft-sql-server-logo.png /.gitignore: -------------------------------------------------------------------------------- 1 | # Prerequisites 2 | *.d 3 | 4 | # Compiled Object files 5 | *.slo 6 | *.lo 7 | *.o 8 | *.obj 9 | 10 | # Precompiled Headers 11 | *.gch 12 | *.pch 13 | 14 | # Compiled Dynamic libraries 15 | *.so 16 | *.dylib 17 | *.dll 18 | 19 | # Fortran module files 20 | *.mod 21 | *.smod 22 | 23 | # Compiled Static libraries 24 | *.lai 25 | *.la 26 | *.a 27 | *.lib 28 | 29 | # Executables 30 | *.exe 31 | *.out 32 | *.app 33 | -------------------------------------------------------------------------------- /Articles/Backup/How to Build a SQL Server Disaster Recovery Plan with Google Compute Engine.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/Articles/Backup/How to Build a SQL Server Disaster Recovery Plan with Google Compute Engine.pdf -------------------------------------------------------------------------------- /Articles/Backup/Optimizing Your Query Plans with the SQL Server 2014 Cardinality Estimator.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/Articles/Backup/Optimizing Your Query Plans with the SQL Server 2014 Cardinality Estimator.docx -------------------------------------------------------------------------------- /Articles/Backup/Permissions_Poster_SQL_Server_2008_R2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/Articles/Backup/Permissions_Poster_SQL_Server_2008_R2.pdf -------------------------------------------------------------------------------- /Articles/Backup/Permissions_Poster_SQL_Server_2012.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/Articles/Backup/Permissions_Poster_SQL_Server_2012.pdf -------------------------------------------------------------------------------- /Articles/Backup/Permissions_Poster_SQL_Server_2014.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/Articles/Backup/Permissions_Poster_SQL_Server_2014.pdf -------------------------------------------------------------------------------- /Articles/Backup/Permissions_Poster_SQL_Server_2016_and_SQLDB.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/Articles/Backup/Permissions_Poster_SQL_Server_2016_and_SQLDB.pdf -------------------------------------------------------------------------------- /Articles/Backup/Permissions_Poster_SQL_Server_vNext_and_SQLDB.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/Articles/Backup/Permissions_Poster_SQL_Server_vNext_and_SQLDB.pdf -------------------------------------------------------------------------------- /Articles/Backup/SQL Server Performance Tuning in Google Compute Engine.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/Articles/Backup/SQL Server Performance Tuning in Google Compute Engine.pdf -------------------------------------------------------------------------------- /Articles/Backup/The Curse and Blessings of Dynamic SQL.htm: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/Articles/Backup/The Curse and Blessings of Dynamic SQL.htm -------------------------------------------------------------------------------- /Articles/Backup/To BLOB or Not To BLOB Large Object Storage in a Database or a Filesystem.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/Articles/Backup/To BLOB or Not To BLOB Large Object Storage in a Database or a Filesystem.pdf -------------------------------------------------------------------------------- /Articles/Backup/sql server on vmware best practices guide.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/Articles/Backup/sql server on vmware best practices guide.pdf -------------------------------------------------------------------------------- /CLR/README.md: -------------------------------------------------------------------------------- 1 | # Microsoft SQL Server CLR 2 | 3 | Useful links: 4 | - [Introduction to SQL Server CLR Integration](https://msdn.microsoft.com/en-us/library/ms254498(v=vs.110).aspx) 5 | - [CLR User-Defined Functions](https://msdn.microsoft.com/library/ms131077.aspx) 6 | - [CLR User-Defined Types](https://msdn.microsoft.com/en-us/library/ms131120(SQL.100).aspx) 7 | - [CLR Stored Procedures](https://msdn.microsoft.com/en-us/library/ms131094(SQL.100).aspx) 8 | - [CLR Triggers](https://msdn.microsoft.com/en-us/library/ms131093(SQL.100).aspx) 9 | - [SQL# CLR functions](https://SQLsharp.com/) (by Sql Quantum Lift) 10 | 11 | The common language runtime (CLR) is the heart of the Microsoft .NET Framework and provides the execution environment for all .NET Framework code. Code that runs within the CLR is referred to as managed code. The CLR provides various functions and services required for program execution, including just-in-time (JIT) compilation, allocating and managing memory, enforcing type safety, exception handling, thread management, and security. 12 | 13 | With the CLR hosted in Microsoft SQL Server (called CLR integration), you can author stored procedures, triggers, user-defined functions, user-defined types, and user-defined aggregates in managed code. Because managed code compiles to native code prior to execution, you can achieve significant performance increases in some scenarios. 14 | 15 | Enabling CLR Integration: 16 | 17 | ```tsql 18 | EXEC sp_configure 'clr enabled', 1; 19 | RECONFIGURE; 20 | GO 21 | ``` 22 | -------------------------------------------------------------------------------- /CLR/Regex/Fill_Factor/InstallRegex.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/CLR/Regex/Fill_Factor/InstallRegex.sql -------------------------------------------------------------------------------- /CLR/Regex/SqlRegularExpressions_SQLServerProject_QuickDeployment.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/CLR/Regex/SqlRegularExpressions_SQLServerProject_QuickDeployment.zip -------------------------------------------------------------------------------- /Errors/Backup/Be aware of 701 error if you use memory optimized table variable in a loop.maff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/Errors/Backup/Be aware of 701 error if you use memory optimized table variable in a loop.maff -------------------------------------------------------------------------------- /Errors/Backup/CREATE DATABASE – I’ve not seen that before..maff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/Errors/Backup/CREATE DATABASE – I’ve not seen that before..maff -------------------------------------------------------------------------------- /Errors/Backup/Case study Troubleshooting Doomed Transactions.maff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/Errors/Backup/Case study Troubleshooting Doomed Transactions.maff -------------------------------------------------------------------------------- /Errors/Backup/Compressed backup errors and TF 3042.maff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/Errors/Backup/Compressed backup errors and TF 3042.maff -------------------------------------------------------------------------------- /Errors/Backup/Nuance of datetime data type in SQL Server.maff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/Errors/Backup/Nuance of datetime data type in SQL Server.maff -------------------------------------------------------------------------------- /Errors/Backup/SQL SERVER - Disabling 15000 Partitions (15k).maff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/Errors/Backup/SQL SERVER - Disabling 15000 Partitions (15k).maff -------------------------------------------------------------------------------- /Errors/Backup/SQL SERVER - FIX Error Msg 8672 - The MERGE Statement Attempted to UPDATE or DELETE the Same Row More Than Once.maff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/Errors/Backup/SQL SERVER - FIX Error Msg 8672 - The MERGE Statement Attempted to UPDATE or DELETE the Same Row More Than Once.maff -------------------------------------------------------------------------------- /Errors/Backup/SQL SERVER - FIX Error 913, Severity 16 - Could Not Find Database ID 3. Database May Not be Activated Yet or May be in Transition.maff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/Errors/Backup/SQL SERVER - FIX Error 913, Severity 16 - Could Not Find Database ID 3. Database May Not be Activated Yet or May be in Transition.maff -------------------------------------------------------------------------------- /Errors/Backup/SQL SERVER - Logon Failure The User has not Been Granted the Requested Logon Type at This Computer.maff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/Errors/Backup/SQL SERVER - Logon Failure The User has not Been Granted the Requested Logon Type at This Computer.maff -------------------------------------------------------------------------------- /Errors/Backup/SQL Server 2016 Online ALTER COLUMN Operation.maff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/Errors/Backup/SQL Server 2016 Online ALTER COLUMN Operation.maff -------------------------------------------------------------------------------- /Errors/Backup/Unable to restore a backup – Msg 3241.maff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/Errors/Backup/Unable to restore a backup – Msg 3241.maff -------------------------------------------------------------------------------- /Errors/Backup/Who owns your availability groups.maff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/Errors/Backup/Who owns your availability groups.maff -------------------------------------------------------------------------------- /Errors/Identity_gap_sql_server_2012.sql: -------------------------------------------------------------------------------- 1 | IF OBJECT_ID('t1', 'U') IS NOT NULL 2 | DROP TABLE t1; 3 | GO 4 | 5 | CREATE TABLE t1 ( 6 | col1 INTEGER IDENTITY(1,1), 7 | col2 VARCHAR(10), 8 | col3 CHAR(10), 9 | col4 NCHAR(10), 10 | col5 TINYINT, 11 | col6 BIGINT 12 | ); 13 | GO 14 | 15 | INSERT INTO t1 (col2, col3, col4, col5, col6) 16 | SELECT 'val1', 'val1', 'val1', 0, 0 17 | UNION ALL 18 | SELECT 'val2', 'val2', 'val2', 255, 255; 19 | 20 | SELECT * 21 | FROM t1; 22 | 23 | DBCC CHECKIDENT('t1', 'NORESEED'); 24 | 25 | -- Restart SQL Server 26 | 27 | DBCC CHECKIDENT('t1', 'NORESEED'); 28 | 29 | INSERT INTO t1 (col2, col3, col4, col5, col6) 30 | VALUES ('val3', 'val3', 'val3', 10, 10), 31 | ('val4', 'val4', 'val4', 100, 100); 32 | 33 | SELECT *, 34 | LEN(col1) AS integer_len, 35 | LEN(col2) AS varchar_len, 36 | LEN(col3) AS char_len, 37 | LEN(col4) AS nchar_len, 38 | LEN(col5) AS tinyint_len, 39 | LEN(col6) AS bigint_len, 40 | DATALENGTH(col1) AS integer_datalength, 41 | DATALENGTH(col2) AS varchar_datalength, 42 | DATALENGTH(col3) AS char_datalength, 43 | DATALENGTH(col4) AS nchar_datalength, 44 | DATALENGTH(col5) AS tinyint_datalength, 45 | DATALENGTH(col6) AS bigint_datalength 46 | FROM t1; 47 | 48 | -- DBCC CHECKIDENT('t1', 'RESEED', 5); 49 | 50 | IF EXISTS (SELECT 1 FROM sys.all_objects sao WHERE sao.name = 't1' AND sao.type = 'U') 51 | DROP TABLE t1 52 | ELSE PRINT 'Table t1 not exist!'; 53 | GO 54 | 55 | BEGIN TRY 56 | SELECT --/* 57 | CAST(-1 AS tinyint), 58 | 1/0 59 | --*/ * FROM t1; 60 | END TRY 61 | BEGIN CATCH 62 | SELECT ERROR_NUMBER() AS ERROR_NUMBER, 63 | ERROR_SEVERITY() AS ERROR_SEVERITY, 64 | ERROR_STATE() AS ERROR_STATE, 65 | ERROR_PROCEDURE() AS ERROR_PROCEDURE, 66 | ERROR_MESSAGE() AS ERROR_MESSAGE, 67 | ERROR_LINE() AS ERROR_LINE; 68 | END CATCH; 69 | -------------------------------------------------------------------------------- /Errors/PDB/README.md: -------------------------------------------------------------------------------- 1 | # SQL Server Debugging 2 | 3 | - [Obtaining symbol files (.PDB) for SQL Server Releases](https://github.com/arvindshmicrosoft/SQLCallStackResolver/wiki/Scripts-to-download-symbols-for-SQL-Server-2019) 4 | - [What is the SOS_WORK_DISPATCHER Wait Type?](https://orderbyselectnull.com/2018/09/27/what-is-the-sos_work_dispatcher-wait-type/) 5 | - [An XEvent a Day (24 of 31) – What is the callstack?](https://www.sqlskills.com/blogs/jonathan/an-xevent-a-day-24-of-31-what-is-the-callstack/) 6 | 7 | This section contains PowerShell scripts which automate the download and extraction of `.PDB` files corresponding to major releases of SQL Server. 8 | 9 | For running any of these scripts, please note the following: 10 | - You must run them within PowerShell, preferably within Windows 11 | - You must have Internet access from the machine running the PowerShell script 12 | - You might want to replace the $outputFolder placeholder with a different folder path (for example, `N:\sqlsymbols\SQL2016SP1`) 13 | - The script will automatically create the folder where the downloaded PDB files are stored. 14 | 15 | Please click on one of the links below depending on the major version of SQL Server that you are looking at: 16 | - [SQL Server 2019](SQL-Server-2019.md) 17 | - [SQL Server 2017](SQL-Server-2017.md) 18 | - [SQL Server 2016](SQL-Server-2016.md) 19 | - [SQL Server 2014](SQL-Server-2014.md) 20 | - [SQL Server 2012](SQL-Server-2012.md) 21 | - [SQL Server 2008 R2](SQL-Server-2008-R2.md) 22 | - [SQL Server 2008](SQL-Server-2008.md) 23 | -------------------------------------------------------------------------------- /Errors/regedit_sqlserver.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/Errors/regedit_sqlserver.png -------------------------------------------------------------------------------- /Extended_Events/ADS_Standard_Azure.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Original link: https://sqlperformance.com/2020/04/sql-performance/bandwidth-friendly-query-profiling-azure-sql-database 3 | Author: Greg Gonzalez 4 | */ 5 | 6 | ALTER EVENT SESSION [ADS_Standard_Azure] ON DATABASE 7 | DROP EVENT sqlserver.attention, 8 | DROP EVENT sqlserver.existing_connection, 9 | DROP EVENT sqlserver.login, 10 | DROP EVENT sqlserver.logout, 11 | DROP EVENT sqlserver.rpc_completed, 12 | DROP EVENT sqlserver.sql_batch_completed, 13 | DROP EVENT sqlserver.sql_batch_starting 14 | GO 15 | 16 | ALTER EVENT SESSION [ADS_Standard_Azure] ON DATABASE 17 | ADD EVENT sqlserver.rpc_completed( 18 | ACTION(package0.event_sequence,sqlserver.client_app_name,sqlserver.client_pid,sqlserver.database_id,sqlserver.query_hash,sqlserver.session_id,sqlserver.username) 19 | WHERE (([package0].[equal_boolean]([sqlserver].[is_system],(0))) AND ([duration] >= (1000000)))), 20 | ADD EVENT sqlserver.sql_batch_completed( 21 | ACTION(package0.event_sequence,sqlserver.client_app_name,sqlserver.client_pid,sqlserver.database_id,sqlserver.query_hash,sqlserver.session_id,sqlserver.username) 22 | WHERE (([package0].[equal_boolean]([sqlserver].[is_system],(0))) AND ([duration] >= (1000000)))) 23 | GO 24 | 25 | ALTER EVENT SESSION [ADS_Standard_Azure] ON DATABASE 26 | DROP TARGET package0.ring_buffer 27 | GO 28 | 29 | ALTER EVENT SESSION [ADS_Standard_Azure] ON DATABASE 30 | ADD TARGET package0.ring_buffer(SET max_events_limit=(10),max_memory=(51200)) 31 | GO 32 | -------------------------------------------------------------------------------- /Extended_Events/APC_Reverted_plan_corrections.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Original link: https://blogs.msdn.microsoft.com/sqlserverstorageengine/2017/07/18/monitoring-automatic-tuning-actions-using-xevents/ 3 | Author: Jovan Popovic 4 | */ 5 | 6 | IF SERVERPROPERTY('ProductMajorVersion') < 14 7 | RAISERROR ('Your version of SQL Server is not supported! This extended event works only for version >= 2017 RC1', 20, 1) WITH LOG; 8 | 9 | IF EXISTS (SELECT 1 FROM sys.server_event_sessions WHERE name = 'APC_Reverted_plan_corrections') 10 | DROP EVENT SESSION [APC_Reverted_plan_corrections] ON SERVER; 11 | GO 12 | 13 | CREATE EVENT SESSION [APC_Reverted_plan_corrections] ON SERVER 14 | ADD EVENT qds.automatic_tuning_plan_regression_verification_check_completed( 15 | WHERE ((([is_regression_detected]=(1)) 16 | AND ([is_regression_corrected]=(1))) 17 | AND ([option_id]=(1)))) 18 | ADD TARGET package0.event_file(SET filename=N'reverted_plan_corrections') 19 | WITH (STARTUP_STATE=ON); 20 | GO 21 | 22 | ALTER EVENT SESSION [APC_Reverted_plan_corrections] ON SERVER STATE = start; 23 | GO 24 | -------------------------------------------------------------------------------- /Extended_Events/APC_plans_that_are_not_corrected.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Original link: https://blogs.msdn.microsoft.com/sqlserverstorageengine/2017/07/18/monitoring-automatic-tuning-actions-using-xevents/ 3 | Author: Jovan Popovic 4 | */ 5 | 6 | IF SERVERPROPERTY('ProductMajorVersion') < 14 7 | RAISERROR ('Your version of SQL Server is not supported! This extended event works only for version >= 2017 RC1', 20, 1) WITH LOG; 8 | 9 | IF EXISTS (SELECT 1 FROM sys.server_event_sessions WHERE name = 'APC_plans_that_are_not_corrected') 10 | DROP EVENT SESSION [APC_plans_that_are_not_corrected] ON SERVER; 11 | GO 12 | 13 | CREATE EVENT SESSION [APC_plans_that_are_not_corrected] ON SERVER 14 | ADD EVENT qds.automatic_tuning_plan_regression_detection_check_completed( 15 | WHERE ((([is_regression_detected]=(1)) 16 | AND ([is_regression_corrected]=(0))) 17 | AND ([option_id]=(1)))) 18 | ADD TARGET package0.event_file(SET filename=N'plans_that_are_not_corrected') 19 | WITH (STARTUP_STATE=ON); 20 | GO 21 | 22 | ALTER EVENT SESSION [APC_plans_that_are_not_corrected] ON SERVER STATE = start; 23 | GO -------------------------------------------------------------------------------- /Extended_Events/AppExecutionTimeout.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Original link: http://blog.sqlgrease.com/how-to-detect-query-timeout-errors-with-extended-events/ 3 | Author: Franklin Yamamoto 4 | 5 | SELECT 6 | object_name 7 | , convert(xml, event_data) AS event_data 8 | , file_name 9 | , file_offset 10 | FROM sys.fn_xe_file_target_read_file(N'AppExecutionTimeout*.xel',NULL,NULL,NULL); 11 | GO 12 | */ 13 | 14 | /* Stop trace if started */ 15 | IF EXISTS (SELECT * FROM sys.dm_xe_sessions WHERE name = 'AppExecutionTimeout') 16 | ALTER EVENT SESSION AppExecutionTimeout ON SERVER STATE = STOP; 17 | 18 | /* Delete trace if exists */ 19 | IF EXISTS (SELECT * FROM sys.server_event_sessions WHERE name = 'AppExecutionTimeout') 20 | DROP EVENT SESSION AppExecutionTimeout ON SERVER; 21 | 22 | /* Create trace */ 23 | CREATE EVENT SESSION AppExecutionTimeout ON SERVER 24 | ADD EVENT sqlserver.attention 25 | (ACTION (sqlserver.session_id, sqlserver.database_id, sqlserver.database_name, 26 | sqlserver.username, sqlserver.sql_text, sqlserver.client_hostname, 27 | sqlserver.client_app_name) 28 | WHERE ([package0].[equal_boolean]([sqlserver].[is_system],(0)))) 29 | ADD TARGET package0.event_file(SET filename=N'AppExecutionTimeout.xel', 30 | max_file_size=(5),max_rollover_files=(2)); 31 | GO 32 | 33 | ALTER EVENT SESSION AppExecutionTimeout ON SERVER STATE = START; 34 | GO 35 | -------------------------------------------------------------------------------- /Extended_Events/BackupRestoreTrace.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Original link: https://blogs.msdn.microsoft.com/sql_server_team/sql-server-mysteries-the-case-of-the-not-100-restore/ 3 | Author: Bob Ward 4 | */ 5 | IF EXISTS ( 6 | SELECT * FROM sys.server_event_sessions 7 | WHERE [name] = N'BackupRestoreTrace') 8 | DROP EVENT SESSION BackupRestoreTrace ON SERVER 9 | GO 10 | 11 | 12 | CREATE EVENT SESSION BackupRestoreTrace ON SERVER 13 | ADD EVENT sqlos.async_io_completed( 14 | ACTION(package0.event_sequence,sqlos.task_address,sqlserver.session_id)), 15 | ADD EVENT sqlos.async_io_requested( 16 | ACTION(package0.event_sequence,sqlos.task_address,sqlserver.session_id)), 17 | ADD EVENT sqlos.task_completed( 18 | ACTION(package0.event_sequence,sqlserver.session_id)), 19 | ADD EVENT sqlos.task_started( 20 | ACTION(package0.event_sequence,sqlserver.session_id)), 21 | ADD EVENT sqlserver.backup_restore_progress_trace( 22 | ACTION(package0.event_sequence,sqlos.task_address,sqlserver.session_id)), 23 | ADD EVENT sqlserver.file_write_completed(SET collect_path=(1) 24 | ACTION(package0.event_sequence,sqlos.task_address,sqlserver.session_id)) 25 | ADD TARGET package0.event_file(SET filename=N'BackupRestoreTrace') 26 | WITH ( 27 | MAX_MEMORY=4096 KB, 28 | EVENT_RETENTION_MODE=ALLOW_SINGLE_EVENT_LOSS, 29 | MAX_DISPATCH_LATENCY=5 SECONDS, 30 | MAX_EVENT_SIZE=0 KB, 31 | MEMORY_PARTITION_MODE=NONE, 32 | TRACK_CAUSALITY=OFF, 33 | STARTUP_STATE=OFF 34 | ); 35 | -------------------------------------------------------------------------------- /Extended_Events/CheckpointTracking.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Original link: https://www.sqlserverscience.com/extended-events/checkpoint-tracking-via-extended-events/ 3 | Author: Max Vernon 4 | */ 5 | 6 | IF NOT EXISTS ( /* only create this session if one doesn't already exist 7 | to prevent inadvertant loss of events. 8 | */ 9 | SELECT 1 10 | FROM sys.server_event_sessions ss 11 | WHERE ss.name = N'CheckpointTracking' 12 | ) 13 | BEGIN 14 | CREATE EVENT SESSION CheckpointTracking 15 | ON SERVER 16 | ADD EVENT sqlserver.checkpoint_begin 17 | ( 18 | ACTION 19 | ( 20 | package0.callstack 21 | , package0.collect_system_time 22 | , package0.event_sequence 23 | , sqlserver.client_app_name 24 | , sqlserver.client_hostname 25 | , sqlserver.database_id 26 | , sqlserver.database_name 27 | , sqlserver.is_system 28 | , sqlserver.session_id 29 | , sqlserver.session_nt_username 30 | , sqlserver.sql_text 31 | ) 32 | ) 33 | , ADD EVENT sqlserver.checkpoint_end 34 | ( 35 | ACTION 36 | ( 37 | package0.callstack 38 | , package0.collect_system_time 39 | , package0.event_sequence 40 | , sqlserver.client_app_name 41 | , sqlserver.client_hostname 42 | , sqlserver.database_id 43 | , sqlserver.database_name 44 | , sqlserver.is_system 45 | , sqlserver.session_id 46 | , sqlserver.session_nt_username 47 | , sqlserver.sql_text 48 | ) 49 | ) 50 | ADD TARGET package0.ring_buffer 51 | ( 52 | SET max_memory = 10240 53 | ) 54 | WITH (STARTUP_STATE=OFF); 55 | END 56 | GO 57 | ALTER EVENT SESSION CheckpointTracking 58 | ON SERVER 59 | STATE = START; 60 | -------------------------------------------------------------------------------- /Extended_Events/DarkQueries.sql: -------------------------------------------------------------------------------- 1 | CREATE EVENT SESSION [DarkQueries] ON SERVER 2 | ADD EVENT sqlserver.sql_statement_recompile( 3 | ACTION(sqlserver.database_id,sqlserver.sql_text) 4 | WHERE ([recompile_cause]=(11))) -- Option (RECOMPILE) Requested 5 | ADD TARGET package0.event_file(SET filename=N'DarkQueries'); 6 | 7 | ALTER EVENT SESSION [DarkQueries] ON SERVER STATE = START; 8 | 9 | 10 | SELECT DarkQueryData.eventDate, 11 | DB_NAME(DarkQueryData.database_id) as DatabaseName, 12 | DarkQueryData.object_type, 13 | COALESCE(DarkQueryData.sql_text, 14 | OBJECT_NAME(DarkQueryData.object_id, DarkQueryData.database_id)) command, 15 | DarkQueryData.recompile_cause 16 | FROM sys.fn_xe_file_target_read_file ( 'DarkQueries*xel', null, null, null) event_file_value 17 | CROSS APPLY ( SELECT CAST(event_file_value.[event_data] as xml) ) event_file_value_xml ([xml]) 18 | CROSS APPLY ( 19 | SELECT event_file_value_xml.[xml].value('(event/@timestamp)[1]', 'datetime') as eventDate, 20 | event_file_value_xml.[xml].value('(event/action[@name="sql_text"]/value)[1]', 'nvarchar(max)') as sql_text, 21 | event_file_value_xml.[xml].value('(event/data[@name="object_type"]/text)[1]', 'nvarchar(100)') as object_type, 22 | event_file_value_xml.[xml].value('(event/data[@name="object_id"]/value)[1]', 'bigint') as object_id, 23 | event_file_value_xml.[xml].value('(event/data[@name="source_database_id"]/value)[1]', 'bigint') as database_id, 24 | event_file_value_xml.[xml].value('(event/data[@name="recompile_cause"]/text)[1]', 'nvarchar(100)') as recompile_cause 25 | ) as DarkQueryData 26 | ORDER BY eventDate DESC; 27 | -------------------------------------------------------------------------------- /Extended_Events/ImplicitConversionOnly.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Original link: https://www.scarydba.com/2018/10/15/using-extended-events-to-capture-implicit-conversions/ 3 | Author: Grant Fritchey 4 | */ 5 | -- If the Event Session exists DROP it 6 | IF EXISTS (SELECT 1 7 | FROM sys.server_event_sessions 8 | WHERE name = N'ImplicitConversionOnly') 9 | DROP EVENT SESSION ImplicitConversionOnly ON SERVER; 10 | 11 | CREATE EVENT SESSION ImplicitConversionOnly 12 | ON SERVER 13 | ADD EVENT sqlserver.plan_affecting_convert 14 | (ACTION (sqlserver.sql_text) 15 | -- WHERE (sqlserver.equal_i_sql_unicode_string(sqlserver.database_name, N'AdventureWorks2017')) 16 | ) 17 | ADD TARGET package0.event_file 18 | (SET filename = N'ImplicitConversionOnly'); 19 | 20 | ALTER EVENT SESSION ImplicitConversionOnly ON SERVER STATE = START; 21 | GO 22 | -------------------------------------------------------------------------------- /Extended_Events/InvestigateWaits.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Original link: http://www.sqlskills.com/blogs/paul/who-is-overriding-maxdop-1-on-the-instance/ 3 | Author: Paul Randal 4 | */ 5 | IF EXISTS ( 6 | SELECT * FROM sys.server_event_sessions 7 | WHERE [name] = N'InvestigateWaits') 8 | DROP EVENT SESSION [InvestigateWaits] ON SERVER 9 | GO 10 | 11 | CREATE EVENT SESSION InvestigateWaits ON SERVER 12 | ADD EVENT sqlserver.degree_of_parallelism 13 | ( 14 | ACTION ( 15 | sqlserver.client_hostname, 16 | sqlserver.nt_username, 17 | sqlserver.sql_text) 18 | WHERE [dop] > 0 -- parallel plans 19 | ) 20 | ADD TARGET [package0].[ring_buffer] 21 | WITH 22 | ( 23 | MAX_MEMORY = 50 MB, 24 | MAX_DISPATCH_LATENCY = 5 SECONDS) 25 | GO 26 | 27 | And the code to parse the XML, and sample output from my query is: 28 | 29 | SELECT 30 | [data1].[value] ('(./@timestamp)[1]', 'datetime') AS [Time], 31 | [data1].[value] ('(./data[@name="dop"]/value)[1]', 'INT') AS [DOP], 32 | [data1].[value] ('(./action[@name="client_hostname"]/value)[1]', 'VARCHAR(MAX)') AS [Host], 33 | [data1].[value] ('(./action[@name="nt_username"]/value)[1]', 'VARCHAR(MAX)') AS [User], 34 | [data1].[value] ('(./action[@name="sql_text"]/value)[1]','VARCHAR(MAX)') AS [Statement] 35 | FROM ( 36 | SELECT CONVERT (XML, [target_data]) AS data 37 | FROM sys.dm_xe_session_targets [xst] 38 | INNER JOIN sys.dm_xe_sessions [xs] 39 | ON [xst].[event_session_address] = [xs].[address] 40 | WHERE [xs].[name] = N'InvestigateWaits') AS t 41 | CROSS APPLY data.nodes('//event') n (data1); 42 | GO 43 | -------------------------------------------------------------------------------- /Extended_Events/LockEscalation.sql: -------------------------------------------------------------------------------- 1 | /* 2 | https://littlekendra.com/2017/04/03/which-locks-count-toward-lock-escalation/ 3 | by Kendra Little Melton 2017-04-03 4 | */ 5 | 6 | DROP EVENT SESSION LockEscalation ON SERVER; 7 | GO 8 | 9 | CREATE EVENT SESSION LockEscalation ON SERVER 10 | ADD EVENT sqlserver.lock_escalation(SET collect_database_name=(1),collect_statement=(1) 11 | ACTION(sqlserver.session_id)) 12 | ADD TARGET package0.event_file(SET filename=N'C:\XE\Lock_Escalation.xel') 13 | WITH (MAX_MEMORY=4096 KB,EVENT_RETENTION_MODE=NO_EVENT_LOSS,MAX_DISPATCH_LATENCY=5 SECONDS,MAX_EVENT_SIZE=0 KB,MEMORY_PARTITION_MODE=NONE,TRACK_CAUSALITY=OFF,STARTUP_STATE=OFF) 14 | GO 15 | -------------------------------------------------------------------------------- /Extended_Events/LoginFailure.sql: -------------------------------------------------------------------------------- 1 | /* 2 | https://blogs.msdn.microsoft.com/sql_pfe_blog/2017/05/04/login-failed-for-xxx-whos-keeps-trying-to-connect-to-my-server/ 3 | */ 4 | 5 | CREATE EVENT SESSION [LoginFailureTrace] ON SERVER 6 | ADD EVENT sqlserver.errorlog_written( ACTION(sqlserver.client_app_name,sqlserver.client_hostname,sqlserver.client_pid)) 7 | ADD TARGET package0.event_file(SET filename=N'LoginFailureTrace',max_file_size=(128)) 8 | WITH (MAX_MEMORY=4096 KB,EVENT_RETENTION_MODE=ALLOW_MULTIPLE_EVENT_LOSS,MAX_DISPATCH_LATENCY=30 SECONDS,MAX_EVENT_SIZE=0 KB,MEMORY_PARTITION_MODE=NONE,TRACK_CAUSALITY=OFF,STARTUP_STATE=OFF) 9 | GO 10 | -------------------------------------------------------------------------------- /Extended_Events/ProcedureWaits.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Original link: https://www.scarydba.com/2018/02/05/wait-statistics-query/ 3 | Author: Grant Fritchey 4 | */ 5 | 6 | CREATE EVENT SESSION ProcedureWaits 7 | ON SERVER 8 | ADD EVENT sqlos.wait_completed 9 | (SET collect_wait_resource = (1) 10 | WHERE (sqlserver.equal_i_sql_unicode_string(sqlserver.database_name, N'AdventureWorks2017'))), 11 | ADD EVENT sqlserver.module_end 12 | (WHERE ( sqlserver.database_name = N'AdventureWorks2017' 13 | AND object_name = N'ProductTransactionHistoryByReference')), 14 | ADD EVENT sqlserver.rpc_completed 15 | (WHERE (sqlserver.database_name = N'AdventureWorks2017')), 16 | ADD EVENT sqlserver.rpc_starting 17 | (WHERE (sqlserver.database_name = N'AdventureWorks2017')) 18 | WITH (TRACK_CAUSALITY = ON); 19 | -------------------------------------------------------------------------------- /Extended_Events/QueryExecutionDetails.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Original link: https://www.scarydba.com/2019/06/03/which-query-used-the-most-cpu-implementing-extended-events/ 3 | Source link: https://github.com/ktaranov/sqlserver-kit/blob/master/Extended_Events/DBRecoveryProgress.sql 4 | Author: Grant Fritchey 5 | */ 6 | 7 | USE master; 8 | GO 9 | 10 | IF EXISTS 11 | ( 12 | SELECT 13 | * 14 | FROM sys.server_event_sessions 15 | WHERE name = 'QueryExecutionDetails' 16 | ) 17 | DROP EVENT SESSION QueryExecutionDetails ON SERVER; 18 | GO 19 | 20 | CREATE EVENT SESSION QueryExecutionDetails 21 | ON SERVER 22 | ADD EVENT sqlserver.rpc_completed 23 | (WHERE (sqlserver.database_name = N'AdventureWorks')), 24 | ADD EVENT sqlserver.rpc_starting 25 | (WHERE (sqlserver.database_name = N'AdventureWorks')), 26 | ADD EVENT sqlserver.sp_statement_completed 27 | (WHERE (sqlserver.database_name = N'AdventureWorks')), 28 | ADD EVENT sqlserver.sql_batch_completed 29 | (WHERE (sqlserver.database_name = N'AdventureWorks')), 30 | ADD EVENT sqlserver.sql_batch_starting 31 | (WHERE (sqlserver.database_name = N'AdventureWorks')), 32 | ADD EVENT sqlserver.sql_statement_completed 33 | (SET collect_statement = (1) 34 | WHERE (sqlserver.database_name = N'AdventureWorks')) 35 | ADD TARGET package0.event_file 36 | (SET filename = N'C:\ExEvents\QueryExecutionDetails.xel') 37 | WITH (TRACK_CAUSALITY = ON); 38 | 39 | ALTER EVENT SESSION QueryExecutionDetails ON SERVER STATE = START; 40 | GO 41 | -------------------------------------------------------------------------------- /Extended_Events/Recompile_Histogram.sql: -------------------------------------------------------------------------------- 1 | CREATE EVENT SESSION Recompile_Histogram ON SERVER 2 | ADD EVENT sqlserver.sql_statement_recompile 3 | ADD TARGET package0.histogram ( 4 | SET filtering_event_name=N'sqlserver.sql_statement_recompile', 5 | source=N'recompile_cause', 6 | source_type=(0) ); 7 | 8 | ALTER EVENT SESSION Recompile_Histogram ON SERVER STATE = START; 9 | 10 | SELECT sv.subclass_name as recompile_cause, 11 | shredded.recompile_count 12 | FROM sys.dm_xe_session_targets AS xet 13 | JOIN sys.dm_xe_sessions AS xe 14 | ON (xe.address = xet.event_session_address) 15 | CROSS APPLY ( SELECT CAST(xet.target_data as xml) ) as target_data_xml ([xml]) 16 | CROSS APPLY target_data_xml.[xml].nodes('/HistogramTarget/Slot') AS nodes (slot_data) 17 | CROSS APPLY ( 18 | SELECT nodes.slot_data.value('(value)[1]', 'int') AS recompile_cause, 19 | nodes.slot_data.value('(@count)[1]', 'int') AS recompile_count 20 | ) as shredded 21 | JOIN sys.trace_subclass_values AS sv 22 | ON shredded.recompile_cause = sv.subclass_value 23 | WHERE xe.name = 'Recompile_Histogram' 24 | AND sv.trace_event_id = 37 -- SP:Recompile; 25 | -------------------------------------------------------------------------------- /Extended_Events/SchemaQueryByUser.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Original link: https://gist.github.com/SQLDBAWithABeard/3a617e04de5db729e941a0fd6ebed7cc 3 | Author: Rob Sewell 4 | */ 5 | 6 | /* Stop trace if started */ 7 | IF EXISTS (SELECT * FROM sys.dm_xe_sessions WHERE name = 'SchemaQueryByUser') 8 | ALTER EVENT SESSION SchemaQueryByUser ON SERVER STATE = STOP; 9 | 10 | /* Delete trace if exists */ 11 | IF EXISTS (SELECT * FROM sys.server_event_sessions WHERE name = 'SchemaQueryByUser') 12 | DROP EVENT SESSION SchemaQueryByUser ON SERVER; 13 | 14 | /* Create trace */ 15 | CREATE EVENT SESSION SchemaQueryByUser ON SERVER 16 | ADD EVENT sqlserver.sql_batch_completed(SET collect_batch_text=(1) 17 | ACTION(sqlserver.database_name, sqlserver.session_server_principal_name) 18 | WHERE ((((((((NOT ([sqlserver].[like_i_sql_unicode_string]([sqlserver].[session_server_principal_name],N'EZCORP\Y%'))) 19 | AND (([sqlserver].[like_i_sql_unicode_string]([batch_text],N'%%')) 20 | OR ([sqlserver].[equal_i_sql_unicode_string]([sqlserver].[database_name],N'')))) 21 | AND (NOT ([sqlserver].[like_i_sql_unicode_string]([batch_text],N'%SELECT CASE WHEN has_dbaccess%END%')))) 22 | AND (NOT ([sqlserver].[like_i_sql_unicode_string]([batch_text],N'%SELECT case when @edition = N''SQL Azure''%')))) 23 | AND (NOT ([sqlserver].[like_i_sql_unicode_string]([batch_text],N'%SERVERPROPERTY(%')))) 24 | AND (NOT ([sqlserver].[like_i_sql_unicode_string]([batch_text],N'%HasMemoryOptimizedObjects from master.sys.master_files mf join master.sys.databases db on mf.database_id%')))) 25 | AND (NOT ([sqlserver].[like_i_sql_unicode_string]([batch_text],N'%database_query_store_options%')))) 26 | AND (NOT ([sqlserver].[like_i_sql_unicode_string]([batch_text],N'%SET SHOWPLAN%'))))) 27 | GO 28 | 29 | ALTER EVENT SESSION SchemaQueryByUser ON SERVER STATE = START; 30 | GO 31 | -------------------------------------------------------------------------------- /Extended_Events/System_Health_Addition.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Original link: https://karaszi.com/looking-for-strange 3 | Author: Tibor Karaszi's 4 | */ 5 | 6 | --Stop trace if started 7 | IF EXISTS (SELECT * FROM sys.dm_xe_sessions WHERE name = 'SystemHealthAddition') 8 | ALTER EVENT SESSION SystemHealthAddition ON SERVER STATE = STOP; 9 | 10 | --Delete trace if exists 11 | IF EXISTS (SELECT * FROM sys.server_event_sessions WHERE name = 'SystemHealthAddition') 12 | DROP EVENT SESSION SystemHealthAddition ON SERVER; 13 | 14 | --Create trace 15 | CREATE EVENT SESSION [SystemHealthAddition] ON SERVER 16 | ADD EVENT sqlserver.attention( 17 | WHERE (package0.greater_than_uint64(database_id,(4)) 18 | AND package0.equal_boolean(sqlserver.is_system,(0)))) , 19 | ADD EVENT sqlserver.auto_stats( 20 | WHERE (package0.greater_than_uint64(database_id,(4)) 21 | AND package0.equal_boolean(sqlserver.is_system,(0)) 22 | AND package0.greater_than_equal_int64(object_id,(1000000)) 23 | AND package0.greater_than_uint64(duration,(10)))), 24 | ADD EVENT sqlserver.database_file_size_change, 25 | ADD EVENT sqlserver.database_started, 26 | ADD EVENT sqlserver.lock_deadlock, 27 | ADD EVENT sqlserver.lock_escalation, 28 | ADD EVENT sqlserver.lock_timeout_greater_than_0, 29 | ADD EVENT sqlserver.long_io_detected, 30 | 31 | --Begin performance section 32 | ADD EVENT qds.query_store_plan_forcing_failed, 33 | ADD EVENT sqlserver.exchange_spill, 34 | ADD EVENT sqlserver.execution_warning, 35 | ADD EVENT sqlserver.hash_spill_details, 36 | ADD EVENT sqlserver.hash_warning, 37 | ADD EVENT sqlserver.optimizer_timeout, 38 | ADD EVENT sqlserver.query_memory_grant_blocking, 39 | ADD EVENT sqlserver.query_memory_grants, 40 | ADD EVENT sqlserver.sort_warning, 41 | ADD EVENT sqlserver.window_spool_ondisk_warning 42 | --End performance section 43 | 44 | ADD TARGET package0.event_counter; 45 | GO 46 | 47 | /* 48 | --Start trace 49 | ALTER EVENT SESSION SystemHealthAddition ON SERVER STATE = START; 50 | */ 51 | -------------------------------------------------------------------------------- /Extended_Events/XE_Truncate.sql: -------------------------------------------------------------------------------- 1 | /* 2 | https://www.sqlservercentral.com/forums/topic/extended-events-capture-truncate-using-object_altered-event 3 | by Evgeny Garaev 2018-06-28 4 | */ 5 | 6 | /* Stop trace if started */ 7 | IF EXISTS (SELECT * FROM sys.dm_xe_sessions WHERE name = N'XE_Truncate') 8 | ALTER EVENT SESSION XE_Truncate ON SERVER STATE = STOP; 9 | 10 | /* Delete trace if exists */ 11 | IF EXISTS (SELECT * FROM sys.server_event_sessions WHERE name = N'XE_Truncate') 12 | DROP EVENT SESSION XE_Truncate ON SERVER; 13 | 14 | 15 | CREATE EVENT SESSION XE_Truncate ON SERVER 16 | ADD EVENT sqlserver.sp_statement_starting(SET collect_statement=(1) 17 | WHERE ([sqlserver].[like_i_sql_unicode_string]([statement], N'truncate table%'))), 18 | ADD EVENT sqlserver.sql_statement_starting(SET collect_statement=(1) 19 | WHERE ([sqlserver].[like_i_sql_unicode_string]([statement],N'truncate table%'))); 20 | GO 21 | 22 | ALTER EVENT SESSION XE_Truncate ON SERVER STATE = START; 23 | GO 24 | -------------------------------------------------------------------------------- /Help/README.md: -------------------------------------------------------------------------------- 1 | # SQL Help 2 | 3 | Need free help? Just follow this simple step: 4 | 1. [Join GitHub](https://github.com/join) 5 | 2. Add star to this repo 6 | 3. Open new issue with a detailed explanation of your problem 7 | 8 | ## How to ask right? 9 | 10 | 1. [Create issue](https://github.com/ktaranov/sqlserver-kit/issues/new) in this repo or question on stackoverflow.com 11 | 2. Include: 12 | 1. Operation system with detailed version (Windows, Ubuntu, Macos etc.). Example: `Microsoft Windows [Version 10.0.16299.248]` 13 | 2. Relation database type (SQL Server preferred, Orcale, MySQL, PostgreSQL, SQLite etc.) with detailed version. Example: `Microsoft SQL Server 2017 (RTM-CU1) (KB4038634) - 14.0.3006.16 (X64) ... on Windows 10 Pro 10.0` 14 | 3. Demo script (if necessary) to reproduce your problem. 15 | 3. Distribute your question using this channels: 16 | 1. [Twitter #sqlhelp](https://twitter.com/search?q=%23sqlhelp&src=tyah) with `#sqlhelp` hash tag 17 | 2. [Slack #sqlhelp](https://sqlcommunity.slack.com/messages/sqlhelp/) (more than 700 People) 18 | 3. [SQLServerCentral Forum](https://www.sqlservercentral.com/Forums/) 19 | 4. Telegram chat (Russian preferred): https://t.me/sqlcom 20 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2015-2021 Konstantin Taranov 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /PowerShell/Compare-Server-Settings.ps1: -------------------------------------------------------------------------------- 1 | #Requires -module dbatools 2 | 3 | <# 4 | .SYNOPSIS 5 | Compare settings for production and development SQL Server instance 6 | 7 | .PARAMETER $productionName 8 | Production server name 9 | 10 | .PARAMETER $productionName 11 | Production server name 12 | 13 | .NOTE 14 | Original link: https://therestisjustcode.wordpress.com/2017/09/12/t-sql-tuesday-94-automating-configuration-comparison/ 15 | Author: Andy Levy 16 | Modified: Konstantin Taranov 2017-09-20 17 | #> 18 | 19 | $productionName = 'localhost'; 20 | $developmentName = 'localhost'; 21 | 22 | $ProductionConfiguration = Get-DbaSpConfigure -ServerInstance $productionName; 23 | # -SqlCredential (Get-Credential -Message "Production Credentials" -UserName MySQLLogin); 24 | $DevelopmentConfiguration = Get-DbaSpConfigure -ServerInstance $developmentName; 25 | Compare-Object -ReferenceObject $DevelopmentConfiguration -DifferenceObject $ProductionConfiguration -property ConfigName, RunningValue | Sort-Object ConfigName; 26 | -------------------------------------------------------------------------------- /PowerShell/Convert_trc_to_2008r2.ps1: -------------------------------------------------------------------------------- 1 | #requires -version 2.0 2 | 3 | <# 4 | .SYNOPSIS 5 | Changes the version information in the header of a SQL Server trace 6 | 7 | .DESCRIPTION 8 | Author: Gianluca Sartori - @spaghettidba 9 | Create date: 2012-11-07 10 | https://spaghettidba.com/2012/11/08/more-on-converting-trace-files/ 11 | 12 | .PARAMETER fileName 13 | Trace file name 14 | #> 15 | 16 | ## ============================================= 17 | ## Author: Gianluca Sartori - @spaghettidba 18 | ## Create date: 2012-11-07 19 | ## Description: Changes the version information 20 | ## in the header of a SQL Server trace 21 | ## ============================================= 22 | $fileName = "somefile.trc" 23 | 24 | # The version information we want to write: 0x0A = 10 = SQLServer 2008 25 | [Byte[]] $versionData = 0x0A 26 | # The offset of the version information in the file 27 | $offset = 390 28 | 29 | [System.IO.FileMode] $open = [System.IO.FileMode]::OpenOrCreate 30 | $stream = New-Object System.IO.FileStream -ArgumentList $fileName, $open 31 | $stream.Seek($offset, [System.IO.SeekOrigin]::Begin); 32 | $stream.Write($versionData, 0, $versionData.Length); 33 | $stream.Close() 34 | -------------------------------------------------------------------------------- /PowerShell/Disable_Enable_All_Triggers_In_Database.ps1: -------------------------------------------------------------------------------- 1 | #requires -version 5.0 2 | #requires -modules dbatools 3 | 4 | <# 5 | .SYNOPSIS 6 | Disable and enable again all triggers in database 7 | 8 | .DESCRIPTION 9 | Disable and enable again all triggers in database 10 | https://jesspomfret.com/disable-all-triggers/ 11 | 12 | .PARAMETER database 13 | Database name 14 | #> 15 | 16 | $database = "AdventureWorks2017"; 17 | $svr = Connect-DbaInstance -SqlInstance server1; 18 | $foreach ($tbl in $svr.databases[$database].Tables) 19 | { 20 | foreach ($tr in $($tbl.Triggers | Where-Object Isenabled)) { 21 | $triggers += $tr | Select-Object @{l='SchemaName';e={$tbl.Schema}}, @{l='TableName';e={$tbl.name}}, @{l='TriggerName';e={$_.name}}; 22 | $tr.isenabled = $FALSE; 23 | $tr.alter(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /PowerShell/Export_Query_To_Csv.ps1: -------------------------------------------------------------------------------- 1 | #requires -version 5.0 2 | #requires -modules sqlserver 3 | 4 | <# 5 | .SYNOPSIS 6 | Export SQL server table to csv file with quotes (if needed) and header 7 | 8 | .DESCRIPTION 9 | Piping Invoke-Sqlcmd into csv file with quotes only if needed. 10 | Also replace False and True on 0 and 1 for bit types columns. 11 | 12 | .NOTES 13 | Original link: http://www.sqlmovers.com/removing-quotes-from-csv-created-by-powershell/ 14 | Author: Russ Loski 15 | Version: 1.3 16 | Modified: 2020-01-09 by Konstantin Taranov 17 | Source link: https://github.com/ktaranov/sqlserver-kit/blob/master/Powershell/Export_Query_To_Csv.ps1 18 | #> 19 | 20 | $databaseName = "master"; 21 | $fileName = $tableName = "sys.objects"; 22 | $delimiter = ","; # possible values "`t", ",", ";", "|" 23 | if ($delimiter -eq "|") { 24 | $delimiterReg = $delimiterBit = "\|"; 25 | } else { 26 | $delimiterReg = $delimiterBit = $delimiter; 27 | }; 28 | $regReplace = '\G(?^|' + $delimiterReg + '+)(("(?[^' + $delimiterReg + '"]*?)"(?=' + $delimiterReg + '|$))|(?".*?(? 10 | 11 | .NOTES 12 | Author: Bill Graziano 13 | Original Link: http://www.sqlteam.com/article/fast-csv-import-in-powershell-to-sql-server 14 | Created Date: 2014-03-18 15 | #> 16 | $streamWriter = New-Object System.IO.StreamWriter ".\SimpleCsvOut3.txt" 17 | $sqlConn = New-Object System.Data.SqlClient.SqlConnection $ConnectionString 18 | $sqlCmd = New-Object System.Data.SqlClient.SqlCommand 19 | $sqlCmd.Connection = $sqlConn 20 | $sqlCmd.CommandText = "SELECT * FROM Test.dbo.CsvImport" 21 | $sqlConn.Open(); 22 | $reader = $sqlCmd.ExecuteReader(); 23 | 24 | # Initialze the arry the hold the values 25 | $array = @() 26 | for ( $i = 0 ; $i -lt $reader.FieldCount; $i++ ) 27 | { $array += @($i) } 28 | 29 | # Write Header 30 | $streamWriter.Write($reader.GetName(0)) 31 | for ( $i = 1; $i -lt $reader.FieldCount; $i ++) 32 | { $streamWriter.Write($("," + $reader.GetName($i))) } 33 | 34 | $streamWriter.WriteLine("") # Close the header line 35 | 36 | while ($reader.Read()) 37 | { 38 | # get the values; 39 | $fieldCount = $reader.GetValues($array); 40 | 41 | # add quotes if the values have a comma 42 | for ($i = 0; $i -lt $array.Length; $i++) 43 | { 44 | if ($array[$i].ToString().Contains(",")) 45 | { 46 | $array[$i] = '"' + $array[$i].ToString() + '"'; 47 | } 48 | } 49 | 50 | $newRow = [string]::Join(",", $array); 51 | 52 | $streamWriter.WriteLine($newRow) 53 | } 54 | $reader.Close(); 55 | $sqlConn.Close(); 56 | $streamWriter.Close(); 57 | -------------------------------------------------------------------------------- /PowerShell/Get-SQLServerGlobalTraceFlags.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .Synopsis 3 | Display all active trace flags on SQL Server 4 | .DESCRIPTION 5 | Display all active trace flags on SQL Server 6 | .EXAMPLE 7 | The following command scripts out the permissions of login account [John] and generates the script at "c:\temp\clone.sql" 8 | Notice, parameters [OldLogin] and [NewLogin] uses the same value of "John" 9 | Clone-SQLLogin -Server Server1, Server2 -OldLogin John -NewLogin John -FilePath "c:\temp\clone.sql" 10 | 11 | .EXAMPLE 12 | Get-SQLServerGlobalTraceFlags 13 | .NOTES 14 | Original link: https://naturalselectiondba.wordpress.com/2016/04/21/sql-server-use-powershell-to-find-what-trace-flags-are-running/ 15 | Author: Matthew Darwin 16 | #> 17 | 18 | function Get-SQLServerGlobalTraceFlags 19 | { 20 | [cmdletbinding()] 21 | param([string]$Server) 22 | 23 | #create an smo object for the SQL Server 24 | $SQLServer = new-object ("Microsoft.SQLServer.Management.Smo.Server") $Server 25 | 26 | #get the trace flag status 27 | $TraceFlags = $SQLServer.EnumActiveGlobalTraceFlags() 28 | 29 | #loop through the trace flags and add the servername in order to create an object with all the required rows to import into a table later 30 | ForEach($TraceFlag in $TraceFlags) 31 | { 32 | $data = @{"ServerName" = $Server 33 | ; "TraceFlag" = $TraceFlag.TraceFlag 34 | ; "Status" = $TraceFlag.Status} 35 | 36 | $Output = new-object psobject -Property $data 37 | write-output $output 38 | } 39 | 40 | } 41 | 42 | export-modulemember -Function Get-SQLServerGlobalTraceFlags 43 | -------------------------------------------------------------------------------- /PowerShell/Get-Windows-Block-Size.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .SYNOPSIS 3 | Get disk block size 4 | .DESCRIPTION 5 | Get disk block size 6 | .PARAMETR 7 | serverList - specify path to server list or live empty 8 | .EXAMPLE 9 | Just run script 10 | .NOTES 11 | Requires: Powershell version 3 or higher 12 | Tested on: Windows 10, 7 13 | Author: Naveen Kumar 14 | Author Modified: Konstantin Tranov kast218@gmail.com 15 | Created date: 2017-09-11 16 | Last modified: 2017-09-11 17 | #> 18 | 19 | $serverList = "C:\ServerList.txt"; 20 | 21 | if(Test-Path $serverList){ 22 | $ServerList = Get-Content $serverList; 23 | Get-WmiObject -Class Win32_volume -Filter "FileSystem='NTFS'" -ComputerName $serverList | Select-Object PSComputerName, Name, Lable, BlockSize | Format-Table -AutoSize; 24 | } 25 | else{ 26 | Get-CimInstance -ClassName Win32_Volume -Filter "FileSystem='NTFS'" | Select-Object Name, Label, BlockSize | Format-Table -AutoSize; 27 | } 28 | -------------------------------------------------------------------------------- /PowerShell/ParameterCaseCheck.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .Synopsis 3 | Search for any parameter that does not match the column name. 4 | 5 | .OUTPUTS 6 | Any parameter that does not match the column name 7 | 8 | .NOTES 9 | Original link: https://nocolumnname.blog/2018/05/25/finding-parameters-that-do-not-match-column-names/ 10 | Author: Shane O'Neill 11 | #> 12 | 13 | $PatternMatch = '(?\w+)\s*=\s*@(?\w+)' 14 | 15 | $FindStoredProcedureParameters = @{ 16 | SqlInstance = 'localhost' 17 | Database = 'master' 18 | Pattern = $PatternMatch 19 | IncludeSystemDatabases = $true 20 | } 21 | 22 | Find-DbaStoredProcedure @FindStoredProcedureParameters | 23 | ForEach-Object -Process { 24 | $ParentRow = $_ 25 | 26 | $_ | ForEach-Object StoredProcedureTextFound | Select-String -Pattern $PatternMatch -AllMatches | ForEach-Object Matches | ForEach-Object -Process { 27 | [PSCustomObject]@{ 28 | ServerName = $ParentRow.SqlInstance 29 | DatabaseName = $ParentRow.Database 30 | SchemaName = $ParentRow.Schema 31 | ProcedureName = $ParentRow.Name 32 | TextFound = ($_.Groups | Where-Object Name -eq '0').Value 33 | ColumnName = ($_.Groups | Where-Object Name -eq 'ColumnName').Value 34 | ParameterName = ($_.Groups | Where-Object Name -eq 'ParameterName').Value 35 | } 36 | } 37 | } | Where-Object { ($_.ColumnName -ne $_.ParameterName) } | 38 | Select-Object -Property * -Unique 39 | -------------------------------------------------------------------------------- /PowerShell/Parse-TSQL.ps1: -------------------------------------------------------------------------------- 1 | #requires -version 5.0 2 | #requires -modules dbatools,pester 3 | 4 | <# 5 | .Synopsis 6 | Ensure that some SQL Scripts in a directory would parse so there was some guarantee that they were valid T-SQL. 7 | 8 | .OUTPUTS 9 | Any invalid TSQL 10 | 11 | .NOTES 12 | Original link: https://sqldbawithabeard.com/2018/07/25/a-powershell-pester-check-for-parsing-sql-scripts/ 13 | Author: Rob Sewell 14 | #> 15 | 16 | Describe "Testing SQL" { 17 | Context "Running Parser" { 18 | ## Load assembly 19 | $dbatoolsPath = 'C:\Program Files\WindowsPowerShell\Modules\dbatools'; 20 | 21 | $Parserdll = (Get-ChildItem $dbatoolsPath -Include Microsoft.SqlServer.Management.SqlParser.dll -Recurse)[0].FullName; 22 | [System.Reflection.Assembly]::LoadFile($Parserdll) | Out-Null; 23 | 24 | $TraceDll = (Get-ChildItem $dbatoolsPath -Include Microsoft.SqlServer.Diagnostics.Strace.dll -Recurse)[0].FullName; 25 | [System.Reflection.Assembly]::LoadFile($TraceDll) | Out-Null; 26 | 27 | $ParseOptions = New-Object Microsoft.SqlServer.Management.SqlParser.Parser.ParseOptions; 28 | $ParseOptions.BatchSeparator = 'GO'; 29 | $files = Get-ChildItem -Path $Env:Directory -Include *.sql -Recurse; ## This variable is set as a Build Process Variable or put your path here 30 | $files.ForEach{ 31 | It "$($Psitem.FullName) Should Parse SQL correctly" { 32 | $filename = $Psitem.FullName; 33 | $sql = Get-Content -LiteralPath "$fileName"; 34 | $Script = [Microsoft.SqlServer.Management.SqlParser.Parser.Parser]::Parse($SQL, $ParseOptions); 35 | $Script.Errors | Should -BeNullOrEmpty; 36 | } 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /PowerShell/Read-XEL-File.ps1: -------------------------------------------------------------------------------- 1 | #requires -version 3.0 2 | 3 | <# 4 | .Synopsis 5 | Read Extended Event .xel file. 6 | 7 | .OUTPUTS 8 | First 50 rows of .xel file delimeted columns by ; and rows by \r\n 9 | 10 | .NOTES 11 | Original link: https://sqlserverpowershell.com/2017/04/06/read-an-extended-events-file-via-powershell/ 12 | Author: Scott Newman 13 | #> 14 | 15 | $xelFilePath = 'c:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLSERVER\MSSQL\Log\system_health_0_131916022434590000.xel'; 16 | $xelDDLPath = 'C:\Program Files\Microsoft SQL Server\140\Shared\'; 17 | 18 | Add-Type -Path ($xelDDLPath+'Microsoft.SqlServer.XE.Core.dll'); 19 | Add-Type -Path ($xelDDLPath+'Microsoft.SqlServer.XEvent.Linq.dll'); 20 | 21 | $events = New-Object Microsoft.SqlServer.XEvent.Linq.QueryableXEventData($xelFilePath) 22 | $sb = New-Object System.Text.StringBuilder 23 | 24 | $events | select -First 50 | %{ 25 | $event = $_ 26 | [void]$sb.Append("$($event.Timestamp);;"); 27 | 28 | for($i=0;$i-lt($event.Fields.Count-1);$i++){ 29 | [void]$sb.Append("$($event.Fields[$i].Value.ToString().Replace("`r`n", ''));;"); 30 | } 31 | 32 | $event.Actions | %{ 33 | $action = $_ 34 | [void]$sb.Append("$($action.value.ToString().Replace("`r`n", ''));;"); 35 | } 36 | [void]$sb.Append("ServerName;;"); 37 | 38 | [void]$sb.AppendLine(); 39 | } 40 | $sb.ToString(); 41 | -------------------------------------------------------------------------------- /PowerShell/Read_XEL_file.ps1: -------------------------------------------------------------------------------- 1 | $path = 'd:\system_health_0_131914905113690000.xel' 2 | 3 | #Add-Type -Path 'C:\Program Files (x86)\Microsoft SQL Server\120\Tools\Binn\ManagementStudio\Extensions\Application\Microsoft.SqlServer.XE.Core.dll' 4 | #Add-Type -Path 'C:\Program Files (x86)\Microsoft SQL Server\120\Tools\Binn\ManagementStudio\Extensions\Application\Microsoft.SqlServer.XEvent.Linq.dll' 5 | 6 | Add-Type -Path 'C:\Program Files\Microsoft SQL Server\120\Shared\Microsoft.SqlServer.XE.Core.dll' 7 | Add-Type -Path 'C:\Program Files\Microsoft SQL Server\120\Shared\Microsoft.SqlServer.XEvent.Linq.dll' 8 | 9 | $events = New-Object Microsoft.SqlServer.XEvent.Linq.QueryableXEventData($path) 10 | $sb = New-Object System.Text.StringBuilder 11 | 12 | $events | select -First 50 | %{ 13 | $event = $_ 14 | [void]$sb.Append("$($event.Timestamp);;"); 15 | 16 | for($i=0;$i-lt($event.Fields.Count-1);$i++){ 17 | [void]$sb.Append("$($event.Fields[$i].Value.ToString().Replace("`r`n", ''));;"); 18 | } 19 | 20 | $event.Actions | %{ 21 | $action = $_ 22 | [void]$sb.Append("$($action.value.ToString().Replace("`r`n", ''));;"); 23 | } 24 | [void]$sb.Append("ServerName;;"); 25 | 26 | [void]$sb.AppendLine(); 27 | } 28 | $sb.ToString(); 29 | -------------------------------------------------------------------------------- /PowerShell/SQL_Server_table_to_csv.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .SYNOPSIS 3 | Export SQL Server table to csv file 4 | .DESCRIPTION 5 | This script export SQL Server table to csv file 6 | .PARAMETER sqlCmd.CommandText 7 | SQL query for export data 8 | .EXAMPLE 9 | C:\PS> 10 | 11 | .NOTES 12 | Author: Bill Graziano 13 | Original Link: http://www.sqlteam.com/article/fast-csv-import-in-powershell-to-sql-server 14 | Created Date: 2014-03-18 15 | #> 16 | $ConnectionString = "localhsot" 17 | $streamWriter = New-Object System.IO.StreamWriter ".\SimpleCsvOut3.txt" 18 | $sqlConn = New-Object System.Data.SqlClient.SqlConnection $ConnectionString 19 | $sqlCmd = New-Object System.Data.SqlClient.SqlCommand 20 | $sqlCmd.Connection = $sqlConn 21 | $sqlCmd.CommandText = "SELECT * FROM sys.tables" 22 | $sqlConn.Open(); 23 | $reader = $sqlCmd.ExecuteReader(); 24 | 25 | # Initialze the arry the hold the values 26 | $array = @() 27 | for ( $i = 0 ; $i -lt $reader.FieldCount; $i++ ) 28 | { $array += @($i) } 29 | 30 | # Write Header 31 | $streamWriter.Write($reader.GetName(0)) 32 | for ( $i = 1; $i -lt $reader.FieldCount; $i ++) 33 | { $streamWriter.Write($("," + $reader.GetName($i))) } 34 | 35 | $streamWriter.WriteLine("") # Close the header line 36 | 37 | while ($reader.Read()) 38 | { 39 | # get the values; 40 | $fieldCount = $reader.GetValues($array); 41 | 42 | # add quotes if the values have a comma 43 | for ($i = 0; $i -lt $array.Length; $i++) 44 | { 45 | if ($array[$i].ToString().Contains(",")) 46 | { 47 | $array[$i] = '"' + $array[$i].ToString() + '"'; 48 | } 49 | } 50 | 51 | $newRow = [string]::Join(",", $array); 52 | 53 | $streamWriter.WriteLine($newRow) 54 | } 55 | $reader.Close(); 56 | $sqlConn.Close(); 57 | $streamWriter.Close(); 58 | -------------------------------------------------------------------------------- /SQL Server Hints.md: -------------------------------------------------------------------------------- 1 | # Microsoft Transact-SQL Hints 2 | 3 | - [Microsoft Transact-SQL Hints](https://docs.microsoft.com/en-us/sql/t-sql/queries/hints-transact-sql) 4 | - [Hints (Transact-SQL) - Join](https://docs.microsoft.com/en-us/sql/t-sql/queries/hints-transact-sql-join) 5 | - [Hints (Transact-SQL) - Table](https://docs.microsoft.com/en-us/sql/t-sql/queries/hints-transact-sql-table) 6 | - [Hints (Transact-SQL) - Query](https://docs.microsoft.com/en-us/sql/t-sql/queries/hints-transact-sql-query) 7 | 8 | **Hint names are case-insensitive.** 9 | 10 | **Some USE HINT hints may conflict with trace flags enabled at the global or session level, or database scoped configuration settings. 11 | In this case, the query level hint (USE HINT) always takes precedence. 12 | If a USE HINT conflicts with another query hint or a trace flag enabled at the query level (such as by QUERYTRACEON), SQL Server will generate an error when trying to execute the query.** 13 | 14 | **Separating hints by spaces rather than commas is a deprecated feature: This feature will be removed in a future version of Microsoft SQL Server. 15 | Do not use this feature in new development work, and modify applications that currently use this feature as soon as possible.** -------------------------------------------------------------------------------- /SSMS/SSMS_Shortcuts.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/SSMS/SSMS_Shortcuts.md -------------------------------------------------------------------------------- /SSMS/SSMS_Snippets/Count Rows Per Partition.snippet: -------------------------------------------------------------------------------- 1 | 2 | 3 | <_locDefinition xmlns="urn:locstudio"> 4 | <_locDefault _loc="locNone" /> 5 | <_locTag _loc="locData">Title 6 | <_locTag _loc="locData">Description 7 | <_locTag _loc="locData">Author 8 | <_locTag _loc="locData">ToolTip 9 | 10 | 11 |
12 | Count rows per partition 13 | 14 | Code Snippet for counting the number of rows in a table per partition. 15 | Matan Yungman 16 | 17 | SurroundsWith 18 | 19 |
20 | 21 | 22 | 25 | 26 | 27 |
28 |
29 | -------------------------------------------------------------------------------- /SSMS/SSMS_Snippets/Count Rows.snippet: -------------------------------------------------------------------------------- 1 | 2 | 3 | <_locDefinition xmlns="urn:locstudio"> 4 | <_locDefault _loc="locNone" /> 5 | <_locTag _loc="locData">Title 6 | <_locTag _loc="locData">Description 7 | <_locTag _loc="locData">Author 8 | <_locTag _loc="locData">ToolTip 9 | 10 | 11 |
12 | Count rows 13 | 14 | Code snippet for counting the number of rows in a table. 15 | Matan Yungman 16 | 17 | SurroundsWith 18 | 19 |
20 | 21 | 22 | 25 | 26 | 27 |
28 |
29 | -------------------------------------------------------------------------------- /SSMS/SSMS_Snippets/Dbcc InputBuffer.snippet: -------------------------------------------------------------------------------- 1 | 2 | 3 | <_locDefinition xmlns="urn:locstudio"> 4 | <_locDefault _loc="locNone" /> 5 | <_locTag _loc="locData">Title 6 | <_locTag _loc="locData">Description 7 | <_locTag _loc="locData">Author 8 | <_locTag _loc="locData">ToolTip 9 | 10 | 11 |
12 | DBCC InputBuffer 13 | 14 | Code snippet for displaying the last statement sent by a specified session. 15 | Matan Yungman 16 | 17 | SurroundsWith 18 | 19 |
20 | 21 | 22 | 25 | 26 | 27 |
28 |
29 | -------------------------------------------------------------------------------- /SSMS/SSMS_Snippets/Index Fragmentation.snippet: -------------------------------------------------------------------------------- 1 | 2 | 3 | <_locDefinition xmlns="urn:locstudio"> 4 | <_locDefault _loc="locNone" /> 5 | <_locTag _loc="locData">Title 6 | <_locTag _loc="locData">Description 7 | <_locTag _loc="locData">Author 8 | <_locTag _loc="locData">ToolTip 9 | 10 | 11 |
12 | Index Fragmentation 13 | 14 | Code snippet for displaying index fragmentation for a given table. 15 | Matan Yungman 16 | 17 | SurroundsWith 18 | 19 |
20 | 21 | 22 | 25 | 26 | 27 |
28 |
29 | -------------------------------------------------------------------------------- /SSMS/SSMS_Snippets/Index Usage.snippet: -------------------------------------------------------------------------------- 1 | 2 | 3 | <_locDefinition xmlns="urn:locstudio"> 4 | <_locDefault _loc="locNone" /> 5 | <_locTag _loc="locData">Title 6 | <_locTag _loc="locData">Description 7 | <_locTag _loc="locData">Author 8 | <_locTag _loc="locData">ToolTip 9 | 10 | 11 |
12 | Index usage 13 | 14 | Code snippet for displaying index usage stats for a given table. 15 | Matan Yungman 16 | 17 | SurroundsWith 18 | 19 |
20 | 21 | 22 | 28 | 29 | 30 |
31 |
32 | -------------------------------------------------------------------------------- /SSMS/SSMS_Snippets/Objects Containing String.snippet: -------------------------------------------------------------------------------- 1 | 2 | 3 | <_locDefinition xmlns="urn:locstudio"> 4 | <_locDefault _loc="locNone" /> 5 | <_locTag _loc="locData">Title 6 | <_locTag _loc="locData">Description 7 | <_locTag _loc="locData">Author 8 | <_locTag _loc="locData">ToolTip 9 | 10 | 11 |
12 | Objects containing string 13 | 14 | Code snippet for displaying progremmatic objects that contain a certain string. 15 | Matan Yungman 16 | 17 | SurroundsWith 18 | 19 |
20 | 21 | 22 | 27 | 28 | 29 |
30 |
31 | -------------------------------------------------------------------------------- /SSMS/SSMS_Snippets/Procedure_dynamic_create.sql: -------------------------------------------------------------------------------- 1 | DECLARE @procedureName SYSNAME = 'dbo.usp_PrintDebug'; 2 | DECLARE @tsqlCommand VARCHAR(MAX) = ''; 3 | 4 | SET @tsqlCommand = 'IF OBJECT_ID(''' + @procedureName + ''', ''P'') IS NULL EXECUTE (''CREATE PROCEDURE ' + @procedureName + ' as select 1''); 5 | GO 6 | 7 | ALTER PROCEDURE ' + @procedureName + ' 8 | 9 | AS 10 | 11 | BEGIN 12 | 13 | SELECT 1 14 | 15 | END;' 16 | 17 | PRINT @tsqlCommand; -------------------------------------------------------------------------------- /SSMS/SSMS_Snippets/SP_HelpIndex.snippet: -------------------------------------------------------------------------------- 1 | 2 | 3 | <_locDefinition xmlns="urn:locstudio"> 4 | <_locDefault _loc="locNone" /> 5 | <_locTag _loc="locData">Title 6 | <_locTag _loc="locData">Description 7 | <_locTag _loc="locData">Author 8 | <_locTag _loc="locData">ToolTip 9 | 10 | 11 |
12 | SP_HelpIndex 13 | 14 | Code snippet for displaying the indexes of a specified table. 15 | Matan Yungman 16 | 17 | SurroundsWith 18 | 19 |
20 | 21 | 22 | 26 | 27 | 28 |
29 |
30 | -------------------------------------------------------------------------------- /SSMS/SSMS_Snippets/Show Current Locks.snippet: -------------------------------------------------------------------------------- 1 | 2 | 3 | <_locDefinition xmlns="urn:locstudio"> 4 | <_locDefault _loc="locNone" /> 5 | <_locTag _loc="locData">Title 6 | <_locTag _loc="locData">Description 7 | <_locTag _loc="locData">Author 8 | <_locTag _loc="locData">ToolTip 9 | 10 | 11 |
12 | Show Current Locks 13 | 14 | Shows current locked objects in the system. 15 | Matan yungman 16 | 17 | Expansion 18 | 19 |
20 | 21 | 22 | 23 | 38 | 39 | 40 |
41 |
42 | -------------------------------------------------------------------------------- /SSMS/SSMS_Snippets/Show Current Running Queries.snippet: -------------------------------------------------------------------------------- 1 | 2 | 3 | <_locDefinition xmlns="urn:locstudio"> 4 | <_locDefault _loc="locNone" /> 5 | <_locTag _loc="locData">Title 6 | <_locTag _loc="locData">Description 7 | <_locTag _loc="locData">Author 8 | <_locTag _loc="locData">ToolTip 9 | 10 | 11 |
12 | Show Current Running Queries 13 | 14 | Shows current running queries with their execution plans. 15 | Matan yungman 16 | 17 | Expansion 18 | 19 |
20 | 21 | 22 | 23 | 33 | 34 | 35 |
36 |
37 | -------------------------------------------------------------------------------- /SSMS/SSMS_Snippets/loop.sql: -------------------------------------------------------------------------------- 1 | DECLARE @startLoop INTEGER = 1960; 2 | DECLARE @endLoop INTEGER = 2012; 3 | DECLARE @columnMask NVARCHAR( 1000 ) = ''; 4 | DECLARE @columns NVARCHAR( MAX ) = ''; 5 | DECLARE @step INTEGER = 1; 6 | DECLARE @debug BIT = 0; 7 | 8 | WHILE( @startLoop <= @endLoop ) 9 | BEGIN 10 | SET @columns = @columns + QUOTENAME( @columnMask + CAST( @startLoop AS NVARCHAR ) ) + ','; 11 | IF @debug = 1 12 | PRINT @columns; 13 | SET @startLoop = @startLoop + @step; 14 | IF @debug = 1 15 | PRINT @startLoop; 16 | END 17 | 18 | PRINT LEFT( @columns, LEN( @columns ) - 1 ); -------------------------------------------------------------------------------- /SSMS/SSMS_Tips/05_ALT+Arrow.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/SSMS/SSMS_Tips/05_ALT+Arrow.gif -------------------------------------------------------------------------------- /SSMS/SSMS_Tips/05_ALT+PASTE.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/SSMS/SSMS_Tips/05_ALT+PASTE.gif -------------------------------------------------------------------------------- /SSMS/SSMS_Tips/24_SSMS_command-line_parameters.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/SSMS/SSMS_Tips/24_SSMS_command-line_parameters.png -------------------------------------------------------------------------------- /SSMS/SSMS_Tips/24_changing_what_ssms_opens_on_startup.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/SSMS/SSMS_Tips/24_changing_what_ssms_opens_on_startup.gif -------------------------------------------------------------------------------- /SSMS/SSMS_Tips/24_changing_what_ssms_opens_on_startup_nosplash.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/SSMS/SSMS_Tips/24_changing_what_ssms_opens_on_startup_nosplash.png -------------------------------------------------------------------------------- /SSMS/SSMS_Tips/24_create_solution_commonly_used_sql_scripts.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/SSMS/SSMS_Tips/24_create_solution_commonly_used_sql_scripts.gif -------------------------------------------------------------------------------- /SSMS/SSMS_Tips/25_query_execution_options.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/SSMS/SSMS_Tips/25_query_execution_options.png -------------------------------------------------------------------------------- /SSMS/SSMS_Tips/25_query_execution_options_ansi.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/SSMS/SSMS_Tips/25_query_execution_options_ansi.png -------------------------------------------------------------------------------- /SSMS/SSMS_Tips/26_sql_server_diagnostics_extension.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/SSMS/SSMS_Tips/26_sql_server_diagnostics_extension.png -------------------------------------------------------------------------------- /SSMS/SSMS_Tips/28_connect_to_sql_servers_in_another_domain_using_windows_authentication_with_credential.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/SSMS/SSMS_Tips/28_connect_to_sql_servers_in_another_domain_using_windows_authentication_with_credential.gif -------------------------------------------------------------------------------- /SSMS/SSMS_Tips/28_connect_to_sql_servers_in_another_domain_using_windows_authentication_with_shortcut.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/SSMS/SSMS_Tips/28_connect_to_sql_servers_in_another_domain_using_windows_authentication_with_shortcut.gif -------------------------------------------------------------------------------- /SSMS/SSMS_Tips/29_SSMS_Database_Default_Reports.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/SSMS/SSMS_Tips/29_SSMS_Database_Default_Reports.png -------------------------------------------------------------------------------- /SSMS/SSMS_Tips/29_SSMS_Server_Default_Reports.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/SSMS/SSMS_Tips/29_SSMS_Server_Default_Reports.png -------------------------------------------------------------------------------- /SSMS/SSMS_Tips/32_object_explore_details_01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/SSMS/SSMS_Tips/32_object_explore_details_01.png -------------------------------------------------------------------------------- /SSMS/SSMS_Tips/32_object_explore_details_02.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/SSMS/SSMS_Tips/32_object_explore_details_02.png -------------------------------------------------------------------------------- /SSMS/SSMS_Tips/32_object_explore_details_03.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/SSMS/SSMS_Tips/32_object_explore_details_03.png -------------------------------------------------------------------------------- /SSMS/SSMS_Tips/38_using_ssms_with_powerbi_01.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/SSMS/SSMS_Tips/38_using_ssms_with_powerbi_01.jpg -------------------------------------------------------------------------------- /SSMS/SSMS_Tips/38_using_ssms_with_powerbi_02.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/SSMS/SSMS_Tips/38_using_ssms_with_powerbi_02.jpg -------------------------------------------------------------------------------- /SSMS/SSMS_Tips/AutoRecover_in_SSMS.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/SSMS/SSMS_Tips/AutoRecover_in_SSMS.png -------------------------------------------------------------------------------- /SSMS/SSMS_Tips/README.md: -------------------------------------------------------------------------------- 1 | # Images for SSMS Tips 2 | 3 | Latest version here: https://github.com/ktaranov/sqlserver-kit/blob/master/SSMS/SSMS_Tips.md 4 | -------------------------------------------------------------------------------- /SSMS/SSMS_Tips/SQL_Vulnerability_Assessment.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/SSMS/SSMS_Tips/SQL_Vulnerability_Assessment.gif -------------------------------------------------------------------------------- /SSMS/SSMS_Tips/additional_connection_parameters.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/SSMS/SSMS_Tips/additional_connection_parameters.png -------------------------------------------------------------------------------- /SSMS/SSMS_Tips/disable_copy_of_empty_text.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/SSMS/SSMS_Tips/disable_copy_of_empty_text.png -------------------------------------------------------------------------------- /SSMS/SSMS_Tips/import_and_export_settings.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/SSMS/SSMS_Tips/import_and_export_settings.png -------------------------------------------------------------------------------- /SSMS/SSMS_Tips/keyboard_shortcuts_for_stored_procedures.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/SSMS/SSMS_Tips/keyboard_shortcuts_for_stored_procedures.png -------------------------------------------------------------------------------- /SSMS/SSMS_Tips/splitting_the_query_window.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/SSMS/SSMS_Tips/splitting_the_query_window.gif -------------------------------------------------------------------------------- /SSMS/SSMS_Tips/ssms_script_objects.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/SSMS/SSMS_Tips/ssms_script_objects.gif -------------------------------------------------------------------------------- /SSMS/SSMS_Tips/ssms_script_objects_server_version.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/SSMS/SSMS_Tips/ssms_script_objects_server_version.png -------------------------------------------------------------------------------- /SSMS/SSMS_Tips/undock_tabs_and_windows_for_multi_monitor_support.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/SSMS/SSMS_Tips/undock_tabs_and_windows_for_multi_monitor_support.gif -------------------------------------------------------------------------------- /SSMS/SSMS_Tips/working_with_tabs_headers.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/SSMS/SSMS_Tips/working_with_tabs_headers.png -------------------------------------------------------------------------------- /SSMS/SSMS_vssettings/README.md: -------------------------------------------------------------------------------- 1 | # SSMS settings files 2 | In files with `_Default_` you can find defaults SSMS settings for different SSMS version. 3 | For import settings files see **tip 1** in [SSMS tips](https://github.com/ktaranov/sqlserver-kit/blob/master/SSMS/SSMS_Tips.md#1) guide. 4 | 5 | My awesome settings: [ktaranov_18.7.1.vssettings](.ktaranov_18.7.1.vssettings) 6 | 7 | - [AB.DarkScheme.LargeFonts.vssettings](/AB.DarkScheme.LargeFonts.vssettings) 8 | - [AB.DarkScheme.NormalFonts.vssettings](/AB.DarkScheme.NormalFonts.vssettings) 9 | - [NewSettings_17.2(14.0.17177).vssettings](/NewSettings_17.2(14.0.17177).vssettings) 10 | - [NewSettings_2014(12.0.5556).vssettings](/NewSettings_2014(12.0.5556).vssettings) 11 | - [NewSettings_Default_17.2(14.0.17177).vssettings](/NewSettings_Default_17.2(14.0.17177).vssettings) 12 | - [NewSettings_Default_18.7.1(15.0.18358).vssettings](/NewSettings_Default_18.7.1(15.0.18358).vssettings) 13 | - [NewSettings_Default_2014(12.0.5556).vssettings](/NewSettings_Default_2014(12.0.5556).vssettings) 14 | -------------------------------------------------------------------------------- /Sample_Databases/Database_script.sql: -------------------------------------------------------------------------------- 1 | SELECT name [Database Name] 2 | , physical_name [File Location] 3 | , ROUND(size * (8.0 / 1024), 0) [Size in MBs] 4 | , * 5 | FROM sys.master_files 6 | WHERE file_id = 1 AND name NOT IN ('master', 'tempdev', 'modeldev', 'MSDBData') 7 | ORDER BY CASE WHEN physical_name LIKE '%StackOverflow2010.mdf' THEN 1 8 | WHEN physical_name LIKE '%StackOverflow.mdf' THEN 2 9 | WHEN physical_name LIKE '%WideWorldImporters.mdf' THEN 3 10 | WHEN physical_name LIKE '%WideWorldImportersDW.mdf' THEN 4 11 | WHEN physical_name LIKE '%AdventureWorks2017.mdf' THEN 5 12 | WHEN physical_name LIKE '%AdventureWorks2016_Data.mdf' THEN 6 13 | WHEN physical_name LIKE '%AdventureWorks2016_EXT_Data.mdf' THEN 7 14 | WHEN physical_name LIKE '%AdventureWorks2014_Data.mdf' THEN 8 15 | WHEN physical_name LIKE '%AdventureWorks2012.mdf' THEN 9 16 | WHEN physical_name LIKE '%AdventureWorksDW2017.mdf' THEN 10 17 | WHEN physical_name LIKE '%AdventureWorksDW2016_Data.mdf' THEN 11 18 | WHEN physical_name LIKE '%AdventureWorksDW2016_EXT_Data.mdf' THEN 12 19 | WHEN physical_name LIKE '%AdventureWorksDW2014_Data.mdf' THEN 13 20 | WHEN physical_name LIKE '%AdventureWorksDW2012.mdf' THEN 14 21 | WHEN physical_name LIKE '%AdventureWorksMultidimensionalModel.mdf' THEN 15 22 | WHEN physical_name LIKE '%AdventureWorksTabularModel.mdf' THEN 16 23 | ELSE 100 24 | END; 25 | -------------------------------------------------------------------------------- /Sample_Databases/PerformanceV3.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/Sample_Databases/PerformanceV3.sql -------------------------------------------------------------------------------- /Sample_Databases/TSQLV4.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/Sample_Databases/TSQLV4.sql -------------------------------------------------------------------------------- /Scripts/Backup_Restore_What’s_My_Status.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Chris Yates 3 | Original link: http://www.sqlservercentral.com/blogs/the-sql-professor/2017/01/26/backuprestorewhats-my-status/ 4 | */ 5 | 6 | --By checking only for the restore and backup command lines you will be able to quickly identify your session id 7 | --and get an approximate ETA and percentage complete. you can tinker of course with the estimations 8 | --if you’d like or pull back more fields. This is just a simple technique in utilizing a helpful DMV to provide info quickly. 9 | SELECT r.session_id 10 | , r.command 11 | , r.start_time 12 | , r.status 13 | , CONVERT(NUMERIC(6, 2), r.percent_complete) AS [Percent Complete] 14 | , CONVERT(VARCHAR(20), DATEADD(ms, r.estimated_completion_time , GETDATE()), 20) AS [ETA Completion Time] 15 | , CONVERT(NUMERIC(10, 2), r.total_elapsed_time / 1000.0 / 60.0) AS [Elapsed Min] 16 | , CONVERT(NUMERIC(10, 2), r.total_elapsed_time / 1000.0 / 60.0 / 60.0) AS [Elapsed Hours] 17 | , CONVERT(NUMERIC(10, 2), r.estimated_completion_time / 1000.0 / 60.0) AS [ETA Min] 18 | , CONVERT(NUMERIC(10, 2), r.estimated_completion_time / 1000.0 / 60.0/ 60.0) AS [ETA Hours] 19 | , CONVERT(VARCHAR(1000), ( 20 | SELECT SUBSTRING(TEXT, r.statement_start_offset / 2, CASE 21 | WHEN r.statement_end_offset = -1 22 | THEN 1000 23 | ELSE (r.statement_end_offset - r.statement_start_offset) / 2 24 | END) 25 | FROM sys.dm_exec_sql_text(sql_handle) 26 | )) AS TSQLStatement 27 | FROM sys.dm_exec_requests r 28 | WHERE command IN ( 29 | 'RESTORE DATABASE' 30 | , 'BACKUP DATABASE' 31 | ); 32 | -------------------------------------------------------------------------------- /Scripts/Bad_Query_Example_13_JOINS.sql: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Generate complex query plan 4 | Reads and writes per database. 5 | 2020-06-23 by Brent Ozar 6 | 2020-07-05 by Konstantin Taranov 7 | 1.1 8 | https://github.com/ktaranov/sqlserver-kit/blob/master/Scripts/Bad_Query_Example_13_JOINS.sql 9 | https://www.brentozar.com/archive/2020/06/bad-idea-jeans-building-big-query-plans/ 10 | 11 | */ 12 | 13 | 14 | DECLARE @TheRootOfAllEvil TABLE 15 | (Id int PRIMARY KEY CLUSTERED); 16 | WITH CTE1 AS (SELECT * FROM @TheRootOfAllEvil r1), 17 | CTE2 AS (SELECT cA.* FROM CTE1 cA INNER JOIN CTE1 cB ON cA.Id = cB.Id), 18 | CTE3 AS (SELECT cA.* FROM CTE2 cA INNER JOIN CTE2 cB ON cA.Id = cB.Id), 19 | CTE4 AS (SELECT cA.* FROM CTE3 cA INNER JOIN CTE3 cB ON cA.Id = cB.Id), 20 | CTE5 AS (SELECT cA.* FROM CTE4 cA INNER JOIN CTE4 cB ON cA.Id = cB.Id), 21 | CTE6 AS (SELECT cA.* FROM CTE5 cA INNER JOIN CTE5 cB ON cA.Id = cB.Id), 22 | CTE7 AS (SELECT cA.* FROM CTE6 cA INNER JOIN CTE6 cB ON cA.Id = cB.Id), 23 | CTE8 AS (SELECT cA.* FROM CTE7 cA INNER JOIN CTE7 cB ON cA.Id = cB.Id), 24 | CTE9 AS (SELECT cA.* FROM CTE8 cA INNER JOIN CTE8 cB ON cA.Id = cB.Id), 25 | CTE10 AS (SELECT cA.* FROM CTE9 cA INNER JOIN CTE9 cB ON cA.Id = cB.Id) 26 | SELECT * FROM CTE10; 27 | -------------------------------------------------------------------------------- /Scripts/CPU_Utilization.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Benjamin Nevarez 3 | Original link: http://sqlblog.com/blogs/ben_nevarez/archive/2009/07/26/getting-cpu-utilization-data-from-sql-server.aspx 4 | */ 5 | 6 | 7 | DECLARE @ts_now BIGINT; 8 | 9 | SELECT @ts_now = cpu_ticks / CONVERT(FLOAT, cpu_ticks) 10 | FROM sys.dm_os_sys_info; 11 | 12 | SELECT record_id 13 | , Dateadd(ms, -1 * ( @ts_now - [timestamp]) 14 | , Getdate()) AS EventTime 15 | , sqlprocessutilization 16 | , systemidle 17 | , 100 - systemidle - sqlprocessutilization AS OtherProcessUtilization 18 | FROM (SELECT record.value('(./Record/@id)[1]', 'int') AS record_id 19 | , record.value('(./Record/SchedulerMonitorEvent/SystemHealth/SystemIdle)[1]', 'int') AS SystemIdle 20 | , record.value('(./Record/SchedulerMonitorEvent/SystemHealth/ProcessUtilization)[1]', 'int') AS SQLProcessUtilization 21 | , timestamp 22 | FROM (SELECT timestamp 23 | , CONVERT(XML, record) AS record 24 | FROM sys.dm_os_ring_buffers 25 | WHERE ring_buffer_type = N'RING_BUFFER_SCHEDULER_MONITOR' 26 | AND record LIKE '%%') AS x) AS y 27 | ORDER BY record_id DESC; 28 | -------------------------------------------------------------------------------- /Scripts/CPU_Utilization_Graphical_form.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Slava Murygin 3 | Original link: http://slavasql.blogspot.ru/2016/03/sql-server-cpu-utilization-in-graphical.html 4 | */ 5 | 6 | DECLARE @gc VARCHAR(MAX), @gi VARCHAR(MAX); 7 | WITH BR_Data as ( 8 | SELECT timestamp, CONVERT(XML, record) as record 9 | FROM sys.dm_os_ring_buffers 10 | WHERE ring_buffer_type = N'RING_BUFFER_SCHEDULER_MONITOR' and record like '%%' 11 | ), Extracted_XML as ( 12 | SELECT timestamp, record.value('(./Record/@id)[1]', 'int') as record_id, 13 | record.value('(./Record/SchedulerMonitorEvent/SystemHealth/SystemIdle)[1]', 'bigint') as SystemIdle, 14 | record.value('(./Record/SchedulerMonitorEvent/SystemHealth/ProcessUtilization)[1]', 'bigint') as SQLCPU 15 | FROM BR_Data 16 | ), CPU_Data as ( 17 | SELECT record_id, ROW_NUMBER() OVER(ORDER BY record_id) as rn, 18 | dateadd(ms, -1 * ((SELECT ms_ticks FROM sys.dm_os_sys_info) - [timestamp]), GETDATE()) as EventTime, 19 | SQLCPU, SystemIdle, 100 - SystemIdle - SQLCPU as OtherCPU 20 | FROM Extracted_XML ) 21 | SELECT @gc = CAST((SELECT CAST(d1.rn as VARCHAR) + ' ' + CAST(d1.SQLCPU as VARCHAR) + ',' FROM CPU_Data as d1 ORDER BY d1.rn FOR XML PATH('')) as VARCHAR(MAX)), 22 | @gi = CAST((SELECT CAST(d1.rn as VARCHAR) + ' ' + CAST(d1.OtherCPU as VARCHAR) + ',' FROM CPU_Data as d1 ORDER BY d1.rn FOR XML PATH('')) as VARCHAR(MAX)) 23 | OPTION (RECOMPILE); 24 | 25 | SELECT CAST('LINESTRING(' + LEFT(@gc,LEN(@gc)-1) + ')' as GEOMETRY), 'SQL CPU %' as Measure 26 | UNION ALL 27 | SELECT CAST('LINESTRING(1 100,2 100)' as GEOMETRY), '' 28 | UNION ALL 29 | SELECT CAST('LINESTRING(' + LEFT(@gi,LEN(@gi)-1) + ')' as GEOMETRY), 'Other CPU %'; 30 | -------------------------------------------------------------------------------- /Scripts/Cached_Data_Per_Object_in_Memory.sql: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | List Cached Data Per Object in Memory 4 | 1 data set: list Cached Data Per Object in Memory. 5 | No 6 | Pinal Dave 7 | 2021-03-31 8 | 2021-03-31 by Konstantin Taranov 9 | 1.0 10 | https://github.com/ktaranov/sqlserver-kit/blob/master/Scripts/Cached_Data_Per_Object_in_Memory.sql 11 | https://blog.sqlauthority.com/2021/03/31/sql-server-cached-data-per-object-in-memory/ 12 | 13 | */ 14 | 15 | SELECT COUNT (1) * 8 / 1024 AS MBUsed, 16 | OBJECT_SCHEMA_NAME(object_id) SchemaName, 17 | name AS TableName, index_id 18 | FROM sys.dm_os_buffer_descriptors AS bd 19 | INNER JOIN 20 | ( 21 | SELECT object_name(object_id) AS name 22 | ,index_id ,allocation_unit_id, object_id 23 | FROM sys.allocation_units AS au 24 | INNER JOIN sys.partitions AS p 25 | ON au.container_id = p.hobt_id 26 | AND (au.type = 1 OR au.type = 3) 27 | UNION ALL 28 | SELECT object_name(object_id) AS name 29 | ,index_id, allocation_unit_id, object_id 30 | FROM sys.allocation_units AS au 31 | INNER JOIN sys.partitions AS p 32 | ON au.container_id = p.partition_id 33 | AND au.type = 2 34 | ) AS obj 35 | ON bd.allocation_unit_id = obj.allocation_unit_id 36 | WHERE database_id = DB_ID() 37 | GROUP BY OBJECT_SCHEMA_NAME(object_id), name, index_id 38 | ORDER BY COUNT (*) * 8 / 1024 DESC; 39 | GO 40 | -------------------------------------------------------------------------------- /Scripts/Checking_Your_Backup_Paths_Exist_and_Automatically_Create_it.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Author: SQL Undercover 3 | Source link: https://sqlundercover.com/2017/09/13/undercover-toolbox-checking-your-backup-paths-exist-and-automatically-creating-them-if-they-dont/ 4 | */ 5 | 6 | --variable to hold directory to check 7 | DECLARE @Path NVARCHAR(300) = N'C:\Test\Backups'; 8 | 9 | IF OBJECT_ID('tempdb..#xp_fileexist_Results') IS NOT NULL DROP TABLE #xp_fileexist_Results; 10 | 11 | CREATE TABLE #xp_fileexist_Results ( 12 | File_Exists int, 13 | File_is_a_Directory int, 14 | Parent_Directory_Exists int 15 | ); 16 | 17 | --check if directory exists 18 | INSERT INTO #xp_fileexist_Results 19 | (File_Exists, File_is_a_Directory, Parent_Directory_Exists) 20 | EXEC master.dbo.xp_fileexist @Path; 21 | 22 | IF EXISTS (SELECT 1 FROM #xp_fileexist_Results WHERE File_is_a_Directory = 1) --if exists PRINT 'Directory Exists' 23 | PRINT 'Directory Exists' 24 | ELSE --if directory doesn't exist, attempt to create it 25 | BEGIN 26 | EXEC xp_create_subdir @Path; 27 | 28 | --perform another existance check to make sure that the directory was actually created 29 | TRUNCATE TABLE #xp_fileexist_Results; 30 | 31 | INSERT INTO #xp_fileexist_Results(File_Exists, File_is_a_Directory, Parent_Directory_Exists) 32 | EXEC master.dbo.xp_fileexist @Path; 33 | 34 | IF EXISTS (SELECT 1 FROM #xp_fileexist_Results WHERE File_is_a_Directory = 1) --if new directory exists PRINT 'Directory Created' 35 | PRINT 'Directory Created' 36 | ELSE 37 | PRINT 'Error Creating Folder' --if new directory doesn't exist then there must have been a problem creating it 38 | END; 39 | GO 40 | -------------------------------------------------------------------------------- /Scripts/Compare_2_tables_by_column_names.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Shane O'Neill 3 | Source link: https://nocolumnname.wordpress.com/2017/04/20/stop-hammer-pivot/ 4 | */ 5 | 6 | SELECT Pivot1.ColumnName, 7 | Pivot1.[dbo.DifferenceTable01], 8 | Pivot1.[dbo.DifferenceTable02], 9 | CASE WHEN [dbo.DifferenceTable01] = 1 AND [dbo.DifferenceTable02] = 1 10 | THEN 'Both' 11 | WHEN [dbo.DifferenceTable01] = 1 AND [dbo.DifferenceTable02] IS NULL 12 | THEN 'Table 1 only' 13 | WHEN [dbo.DifferenceTable01] IS NULL AND [dbo.DifferenceTable02] = 1 14 | THEN 'Table 2 only' 15 | ELSE 'Eh...this should not really happen' 16 | END AS HumanReadableFormat 17 | FROM ( SELECT 18 | c.[name] AS ColumnName, 19 | tb.TableName, 20 | 1 AS ColumnExists 21 | FROM sys.columns AS c 22 | RIGHT JOIN ( VALUES 23 | (OBJECT_ID(N'dbo.DifferenceTable01', N'U'), 'dbo.DifferenceTable01'), 24 | (OBJECT_ID(N'dbo.DifferenceTable02', N'U'), 'dbo.DifferenceTable02') 25 | ) AS tb (ObjectID, TableName) 26 | ON c.object_id = tb.ObjectID 27 | ) AS UnPivotedColumns 28 | PIVOT ( 29 | MAX(ColumnExists) FOR TableName IN ([dbo.DifferenceTable01], [dbo.DifferenceTable02]) 30 | ) AS Pivot1 31 | ORDER BY Pivot1.ColumnName ASC; 32 | -------------------------------------------------------------------------------- /Scripts/Count character matches.sql: -------------------------------------------------------------------------------- 1 | -- MS SQL Server function LEN() does not count trailing spaces! 2 | DECLARE @pattern varchar(20) = 'Ted '; 3 | DECLARE @columnToSearch VARCHAR(1000) = 'Ted is Ted because Ted is awesome!'; 4 | 5 | SELECT (DATALENGTH(@columnToSearch) - DATALENGTH(REPLACE(@columnToSearch, @pattern, ''))) / DATALENGTH(@pattern) DatalengthNumberOfMatches 6 | , (LEN(@columnToSearch) - LEN(REPLACE(@columnToSearch, @pattern, ''))) / Len(@pattern) AS LenNumberOfMatches 7 | , (LEN(@columnToSearch) - LEN(REPLACE(@columnToSearch, @pattern, ''))) AS LenPattern 8 | , LEN(@pattern) AS Len@pattern 9 | , DATALENGTH(@pattern) AS Datalength@pattern; 10 | -------------------------------------------------------------------------------- /Scripts/Count_Database_Reads_and_Writes.sql: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Counts reads and writes for databases 4 | Reads and writes per database. 5 | 2020-04-07 by Brent Ozar 6 | 2020-04-15 by Konstantin Taranov 7 | 1.1 8 | https://github.com/ktaranov/sqlserver-kit/blob/master/Scripts/Count_Database_Reads_and_Writes.sql 9 | https://www.brentozar.com/archive/2020/04/how-can-i-measure-if-my-database-does-more-reads-than-writes/ 10 | 11 | */ 12 | 13 | 14 | WITH reads_and_writes AS ( 15 | SELECT db.name AS database_name, 16 | SUM(user_seeks + user_scans + user_lookups) AS reads, 17 | SUM(user_updates) AS writes, 18 | SUM(user_seeks + user_scans + user_lookups + user_updates) AS all_activity 19 | FROM sys.dm_db_index_usage_stats us 20 | INNER JOIN sys.databases db ON us.database_id = db.database_id 21 | GROUP BY db.name 22 | ) 23 | SELECT 24 | database_name 25 | , reads 26 | , ((reads * 1.0) / all_activity) * 100 AS reads_percent 27 | , writes 28 | , ((writes * 1.0) / all_activity) * 100 AS writes_percent 29 | FROM reads_and_writes AS rw 30 | ORDER BY database_name; 31 | -------------------------------------------------------------------------------- /Scripts/Create_2_Million_Tables.sql: -------------------------------------------------------------------------------- 1 | /* 2 | https://docs.microsoft.com/en-us/sql/sql-server/maximum-capacity-specifications-for-sql-server 3 | Database objects include objects such as tables, views, stored procedures, user-defined functions, triggers, rules, defaults, and constraints. 4 | The sum of the number of all objects in a database cannot exceed 2,147,483,647. 5 | */ 6 | CREATE DATABASE [TwoMillion]; 7 | 8 | ALTER DATABASE [TwoMillion] SET RECOVERY SIMPLE WITH NO_WAIT; 9 | GO 10 | 11 | USE [TwoMillion]; 12 | 13 | SET NOCOUNT ON; 14 | 15 | DECLARE @sql nvarchar(max) = N''; 16 | DECLARE @i int = 1; 17 | 18 | SELECT @i = 2147483647 - COUNT(*) FROM [TwoMillion].sys.objects; 19 | PRINT N'Creating ' + FORMAT(@i,'N0') + N' tables...'; 20 | 21 | WHILE @i > 0 22 | BEGIN 23 | SET @i -= 1; 24 | 25 | SET @sql = N'CREATE TABLE [TwoMillion].dbo.t' + CONVERT(nvarchar(max),2147483648-@i) + N' (i int);'; 26 | IF (@i % 10000) = 0 RAISERROR(@sql, 0, 1) WITH NOWAIT; 27 | 28 | EXEC sp_executesql @sql; 29 | END; 30 | 31 | /* 32 | ALTER DATABASE [TwoMillion] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; 33 | GO 34 | 35 | USE master; 36 | GO 37 | 38 | DROP DATABASE [TwoMillion]; 39 | */ 40 | -------------------------------------------------------------------------------- /Scripts/Database_Mail_Problems.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/Scripts/Database_Mail_Problems.sql -------------------------------------------------------------------------------- /Scripts/Disable_Enable_All_Triggers_In_Database.sql: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Disable and enable again all triggers in database 4 | nothing. 5 | No 6 | Federico Minca 7 | 2019-08-20 8 | 2019-08-26 by Konstantin Taranov 9 | 1.0 10 | https://github.com/ktaranov/sqlserver-kit/blob/master/Scripts/Disable_Enable_All_Triggers_In_Database.sql 11 | https://jesspomfret.com/disable-all-triggers/ 12 | 13 | */ 14 | 15 | -- Select Active Triggers and prepare Disable and Enable T-SQL Statement and put into Temp Table 16 | SELECT 'ALTER TABLE [' + sc.name + '].[' + ta.name + '] DISABLE TRIGGER [' + tr.name + '];' AS DisableTriggerStatement, 17 | 'ALTER TABLE [' + sc.name + '].[' + ta.name + '] ENABLE TRIGGER [' + tr.name + '];' AS EnableTriggerStatement 18 | INTO #Triggers 19 | FROM sys.triggers tr 20 | INNER JOIN sys.tables ta ON ta.object_id = tr.parent_id 21 | INNER JOIN sys.schemas sc ON sc.schema_id = ta.schema_id 22 | WHERE tr.is_disabled = 0; 23 | 24 | -- Perpare Variable Script for Execution 25 | DECLARE @Disable_Statement nvarchar(max) = ( 26 | SELECT tmp.DisableTriggerStatement + CHAR(10) AS "data()" 27 | FROM #Triggers tmp 28 | FOR XML PATH('') 29 | ); 30 | 31 | -- Execute SQL 32 | EXEC sys.sp_executesql @Disable_Statement; 33 | 34 | -- Perpare Variable Script for Execution 35 | DECLARE @Enable_Statement nvarchar(max) = ( 36 | SELECT tmp.DisableTriggerStatement + CHAR(10) AS "data()" 37 | FROM #Triggers tmp 38 | FOR XML PATH('') 39 | ); 40 | 41 | -- Execute SQL 42 | EXEC sys.sp_executesql @Enable_Statement; 43 | 44 | DROP TABLE #Triggers; 45 | -------------------------------------------------------------------------------- /Scripts/Dynamic_GRANT_Generation.sql: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Dynamically generate GRANTs. 4 | PRINT dynamically generated GRANTs for user. 5 | ? 6 | 2020-02-08 by Konstantin Taranov 7 | 1.0 8 | https://github.com/ktaranov/sqlserver-kit/blob/master/Scripts/Dynamic_GRANT_Generation.sql 9 | 10 | */ 11 | 12 | 13 | SET NOCOUNT ON; 14 | SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; 15 | 16 | DECLARE @userName sysname = QUOTENAME(N'user_name'); 17 | DECLARE @tsql nvarchar(max) = N''; 18 | 19 | SELECT @tsql = @tsql + 'GRANT SELECT, INSERT, UPDATE, DELETE ON ' + 20 | QUOTENAME(SCHEMA_NAME("schema_id")) + N'.' + 21 | QUOTENAME("name") + N' TO ' + @userName + N';' + CHAR(13) + CHAR(10) 22 | FROM sys.tables 23 | /* 24 | WHERE "name" NOT IN ('') 25 | --*/ 26 | ; 27 | 28 | IF LEN(@tsql) <= 8000 29 | BEGIN 30 | PRINT(@tsql); 31 | END; 32 | ELSE 33 | BEGIN 34 | SELECT @tsql; 35 | END; 36 | -------------------------------------------------------------------------------- /Scripts/DynamicallyGenerateDMAStatement.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Kenneth Fisher 3 | Original link: https://sqlstudies.com/2017/06/21/query-to-run-command-line-dma-on-each-database 4 | */ 5 | -- Dynamically generate the command line DMA statement for each database 6 | 7 | SELECT name, '"C:\Program Files\Microsoft Data Migration Assistant\DmaCmd.exe" ' + 8 | '/AssessmentName="DMA_Output" ' + 9 | '/AssessmentDatabases="Server=' + @@ServerName + 10 | ';Initial Catalog=' + sys.databases.name + 11 | ';Integrated Security=true" ' + 12 | '/AssessmentEvaluateCompatibilityIssues /AssessmentOverwriteResult ' + 13 | '/AssessmentResultCSV="\\PathToSaveTo\'+REPLACE(@@ServerName,'\','_')+'\'+sys.databases.name+'.CSV"' + 14 | ' > "\\PathToSaveTo\'+REPLACE(@@ServerName,'\','_')+'\'+sys.databases.name+'.LOG"' 15 | FROM sys.databases WHERE state <> 6 -- exclude offline databases 16 | and database_id > 4 -- Exclude system databases 17 | -------------------------------------------------------------------------------- /Scripts/Enable Microsoft.ACE.OLEDB.12.0.sql: -------------------------------------------------------------------------------- 1 | -- https://social.msdn.microsoft.com/Forums/en-US/1d5c04c7-157f-4955-a14b-41d912d50a64/how-to-fix-error-the-microsoftaceoledb120-provider-is-not-registered-on-the-local-machine 2 | 3 | USE master; 4 | 5 | EXEC sp_configure 'show advanced options', 1; 6 | RECONFIGURE; 7 | EXEC sp_configure 'Ad Hoc Distributed Queries', 1; 8 | RECONFIGURE; 9 | GO 10 | EXEC sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'AllowInProcess', 1 11 | GO 12 | EXEC sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'DynamicParameters', 1 13 | GO 14 | -------------------------------------------------------------------------------- /Scripts/Estimate_When_Long_Running_SQL_Processes_Will_Finish.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Tim Ford 3 | Original link: http://sqlmag.com/database-administration/estimate-when-long-running-sql-processes-will-finish 4 | */ 5 | 6 | SET NOCOUNT ON; 7 | 8 | SELECT R.session_id 9 | , R.percent_complete 10 | , R.total_elapsed_time/1000 AS elapsed_seconds 11 | , R.wait_type 12 | , R.wait_time 13 | , R.last_wait_type 14 | , DATEADD(s,100/((R.percent_complete)/ (R.total_elapsed_time/1000)), R.start_time) AS est_complete_time 15 | , ST.text AS batch_text 16 | , CAST(SUBSTRING(ST.text, R.statement_start_offset / 2, 17 | ( 18 | CASE WHEN R.statement_end_offset = -1 THEN DATALENGTH(ST.text) 19 | ELSE R.statement_end_offset 20 | END - R.statement_start_offset 21 | ) / 2 22 | ) AS varchar(1024)) AS statement_executing 23 | FROM sys.dm_exec_requests AS R 24 | CROSS APPLY sys.dm_exec_sql_text(R.sql_handle) AS ST 25 | WHERE R.percent_complete > 0 26 | AND R.session_id <> @@spid; 27 | -------------------------------------------------------------------------------- /Scripts/Extract_Scale_Part_From_Decimal_Number.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Pinal Dave 3 | Created Date: 2018-09-12 4 | Original link: https://blog.sqlauthority.com/2018/09/12/sql-server-simple-method-to-extract-scale-part-from-decimal-number/ 5 | Source link: https://github.com/ktaranov/sqlserver-kit/blob/master/Scripts/Extract_Scale_Part_From_Decimal_Number.sql 6 | Modified: 2018-01-29 by Konstantin Taranov 7 | */ 8 | 9 | IF OBJECT_ID(N'tempdb..#Numbers', 'U') IS NOT NULL DROP TABLE #Numbers; 10 | 11 | CREATE TABLE #Numbers (DecimalValue DECIMAL(16, 10) NOT NULL); 12 | 13 | INSERT INTO #Numbers(DecimalValue) VALUES (100.0000000001); 14 | INSERT INTO #Numbers(DecimalValue) VALUES (-23.8900000098); 15 | INSERT INTO #Numbers(DecimalValue) VALUES (390.077); 16 | INSERT INTO #Numbers(DecimalValue) VALUES (12.87); 17 | INSERT INTO #Numbers(DecimalValue) VALUES (390.1); 18 | 19 | SELECT DecimalValue 20 | , ABS(DecimalValue)%1 AS DecimalScale 21 | FROM #Numbers; 22 | GO 23 | -------------------------------------------------------------------------------- /Scripts/Failed_SQL_Server_Agent_Jobs_With_Restart_Command.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Max Vernon 3 | Created Date: 2019-02-05 4 | Original link: https://blog.sqlauthority.com/2018/09/12/sql-server-simple-method-to-extract-scale-part-from-decimal-number/ 5 | Source link: https://github.com/ktaranov/sqlserver-kit/blob/master/Scripts/Failed_SQL_Server_Agent_Jobs_With_Restart_Command.sql 6 | Modified: 2019-02-11 by Konstantin Taranov 7 | */ 8 | 9 | WITH sys_job_history AS 10 | ( 11 | SELECT * 12 | , rn = ROW_NUMBER() OVER (PARTITION BY sjh.job_id ORDER BY msdb.dbo.agent_datetime(sjh.run_date, sjh.run_time) DESC) 13 | FROM msdb.dbo.sysjobhistory sjh 14 | WHERE sjh.step_id > 0 15 | AND sjh.run_date > CONVERT(int, CONVERT(varchar(8), DATEADD(DAY, -1, GETDATE()), 112)) 16 | ) 17 | SELECT sj.name 18 | , sjh.step_name 19 | , sjh.step_id 20 | , sjh.sql_message_id 21 | , sjh.sql_severity 22 | , sjh.message 23 | , sjh.server 24 | , RunDateTime = msdb.dbo.agent_datetime(sjh.run_date, sjh.run_time) 25 | , StartJobCommand = N'EXEC msdb.dbo.sp_start_job @job_name = ''' + sj.name + N''', @step_name = ''' + sjh.step_name + N''';' 26 | FROM sys_job_history sjh 27 | INNER JOIN msdb.dbo.sysjobs sj ON sjh.job_id = sj.job_id 28 | INNER JOIN msdb.dbo.sysjobschedules sjsch ON sj.job_id = sjsch.job_id 29 | INNER JOIN msdb.dbo.sysschedules ss ON sjsch.schedule_id = ss.schedule_id 30 | WHERE sjh.rn = 1 31 | AND sjh.run_status = 0 --failed 32 | AND ss.enabled = 1 33 | ORDER BY sj.name; 34 | -------------------------------------------------------------------------------- /Scripts/Fast_alternative_to_sp_WhoIsActive.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Arthur Daniels 3 | Created Date: 2019-01-29 4 | Original link: https://blog.sqlauthority.com/2018/09/12/sql-server-simple-method-to-extract-scale-part-from-decimal-number/ 5 | Source link: https://github.com/ktaranov/sqlserver-kit/blob/master/Scripts/Fast_alternative_to_sp_WhoIsActive.sql 6 | Modified: 2018-01-29 by Konstantin Taranov 7 | */ 8 | 9 | SELECT s.session_id, 10 | r.start_time, 11 | s.host_name, 12 | s.login_name, 13 | i.event_info, 14 | r.status, 15 | s.program_name, 16 | r.writes, 17 | r.reads, 18 | r.logical_reads, 19 | r.blocking_session_id, 20 | r.wait_type, 21 | r.wait_time, 22 | r.wait_resource 23 | FROM sys.dm_exec_requests AS r 24 | INNER JOIN sys.dm_exec_sessions AS s ON s.session_id = r.session_id 25 | CROSS APPLY sys.dm_exec_input_buffer(s.session_id, r.request_id) as i 26 | WHERE s.session_id <> @@SPID AND 27 | s.is_user_process = 1; 28 | --Remove the line above if you want to see system processes 29 | -------------------------------------------------------------------------------- /Scripts/FindDBConnectionLeaks.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Michael J Swart (@MJSwart) 3 | Original link: https://sqlperformance.com/2017/07/sql-performance/find-database-connection-leaks 4 | Desctiption: Find Database Connection Leaks in Your Application 5 | */ 6 | 7 | --Finding Your Connection Leaks 8 | 9 | select count(*) as sessions, 10 | s.host_name, 11 | s.host_process_id, 12 | s.program_name, 13 | db_name(s.database_id) as database_name 14 | from sys.dm_exec_sessions s 15 | where is_user_process = 1 16 | group by host_name, host_process_id, program_name, database_id 17 | order by count(*) desc; 18 | 19 | 20 | --Given a pool, are there sessions that have been sleeping for a while and, if so, 21 | --how long have they been sleeping and what was the last SQL statement they executed? 22 | 23 | declare @host_process_id int = 1508; 24 | declare @host_name sysname = N'SERV4102'; 25 | declare @database_name sysname = N'My_Database'; 26 | 27 | select datediff(minute, s.last_request_end_time, getdate()) as minutes_asleep, 28 | s.session_id, 29 | db_name(s.database_id) as database_name, 30 | s.host_name, 31 | s.host_process_id, 32 | t.text as last_sql, 33 | s.program_name 34 | from sys.dm_exec_connections c 35 | join sys.dm_exec_sessions s 36 | on c.session_id = s.session_id 37 | cross apply sys.dm_exec_sql_text(c.most_recent_sql_handle) t 38 | where s.is_user_process = 1 39 | and s.status = 'sleeping' 40 | and db_name(s.database_id) = @database_name 41 | and s.host_process_id = @host_process_id 42 | and s.host_name = @host_name 43 | and datediff(second, s.last_request_end_time, getdate()) > 60 44 | order by s.last_request_end_time; 45 | -------------------------------------------------------------------------------- /Scripts/Find_Maximum_Float_Values.sql: -------------------------------------------------------------------------------- 1 | /* 2 | https://docs.microsoft.com/en-us/sql/t-sql/data-types/float-and-real-transact-sql 3 | */ 4 | 5 | SELECT CAST(-2.22999999999999E-308 AS float(53)) AS "Float(53) Negative Max" 6 | , CAST(-1.797693134862315807E+308 AS float(53)) AS "Float(53) Negative Min" 7 | , CAST(+1.797693134862315807E+308 AS float(53)) AS "Float(53) Positive Max"; 8 | 9 | 10 | SET NOCOUNT ON; 11 | 12 | DROP TABLE IF EXISTS t; 13 | CREATE TABLE t ( 14 | i int IDENTITY(1, 1) NOT NULL 15 | , f float(53) NOT NULL 16 | , s varchar(100) NOT NULL 17 | ); 18 | GO 19 | 20 | DECLARE @s varchar(100) = '+1.79'; /* +1.79 -2.22*/ 21 | DECLARE @i int = 1; 22 | DECLARE @j int = 9; 23 | 24 | WHILE (@i < 200 AND LEN(@s) < 22) 25 | BEGIN 26 | BEGIN TRY 27 | SET @i = @i + 1; 28 | 29 | INSERT INTO t(f, s) SELECT CAST((@s + CAST(@j AS varchar) + 'E' + LEFT(@s, 1) + '308') AS float(53)), @s AS s; 30 | SET @s = (@s + CAST(@j AS varchar)); 31 | SET @j = 9; 32 | END TRY 33 | 34 | BEGIN CATCH 35 | SELECT ERROR_NUMBER() AS ErrorNumber 36 | ,ERROR_SEVERITY() AS ErrorSeverity 37 | ,ERROR_STATE() AS ErrorState 38 | ,ERROR_PROCEDURE() AS ErrorProcedure 39 | ,ERROR_LINE() AS ErrorLine 40 | ,ERROR_MESSAGE() AS ErrorMessage; 41 | SET @j = @j - 1; 42 | END CATCH 43 | END; 44 | 45 | SELECT i, f, s 46 | FROM t 47 | WHERE f = (SELECT MAX(f) AS FLOAT_MAX FROM t); 48 | -------------------------------------------------------------------------------- /Scripts/Find_Non_Sargable_Queries.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Bert Wagner 3 | Source link: https://blog.bertwagner.com/how-to-search-and-destroy-non-sargable-queries-on-your-server-ff9f57c7268e 4 | */ 5 | 6 | SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; 7 | 8 | DECLARE @dbname SYSNAME; 9 | SET @dbname = QUOTENAME(DB_NAME()); 10 | 11 | --WITH XMLNAMESPACES (DEFAULT 'http://schemas.microsoft.com/sqlserver/2004/07/showplan') 12 | 13 | SELECT 14 | stmt.value('(@StatementText)[1]', 'varchar(max)') AS [Query], 15 | query_plan AS [QueryPlan], 16 | sc.value('(.//Identifier/ColumnReference/@Schema)[1]', 'varchar(128)') AS [Schema] 17 | , sc.value('(.//Identifier/ColumnReference/@Table)[1]', 'varchar(128)') AS [Table] 18 | , sc.value('(.//Identifier/ColumnReference/@Column)[1]', 'varchar(128)') AS [Column] 19 | , CASE WHEN s.exist('.//TableScan') = 1 THEN 'TableScan' ELSE 'IndexScan' END AS [ScanType], 20 | sc.value('(@ScalarString)[1]', 'varchar(128)') AS [ScalarString] 21 | FROM 22 | sys.dm_exec_cached_plans AS cp 23 | CROSS APPLY sys.dm_exec_query_plan(cp.plan_handle) AS qp 24 | CROSS APPLY query_plan.nodes('/ShowPlanXML/BatchSequence/Batch/Statements/StmtSimple') AS batch(stmt) 25 | CROSS APPLY stmt.nodes('.//RelOp[TableScan or IndexScan]') AS scan(s) 26 | CROSS APPLY s.nodes('.//ScalarOperator') AS scalar(sc) 27 | WHERE 28 | s.exist('.//ScalarOperator[@ScalarString]!=""') = 1 29 | AND sc.exist('.//Identifier/ColumnReference[@Database=sql:variable("@dbname")][@Schema!="[sys]"]') = 1 30 | AND sc.value('(@ScalarString)[1]', 'varchar(128)') IS NOT NULL; 31 | -------------------------------------------------------------------------------- /Scripts/FindingImplicitColumnConversionsInPlanCache.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Jonathan Kehayias 3 | Original link: https://www.sqlskills.com/blogs/jonathan/finding-implicit-column-conversions-in-the-plan-cache 4 | Desctiption: Finding Implicit Column Conversions in the Plan Cache 5 | */ 6 | 7 | 8 | SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED 9 | 10 | DECLARE @dbname SYSNAME 11 | SET @dbname = QUOTENAME(DB_NAME()); 12 | 13 | WITH XMLNAMESPACES 14 | (DEFAULT 'http://schemas.microsoft.com/sqlserver/2004/07/showplan') 15 | SELECT 16 | stmt.value('(@StatementText)[1]', 'varchar(max)'), 17 | t.value('(ScalarOperator/Identifier/ColumnReference/@Schema)[1]', 'varchar(128)'), 18 | t.value('(ScalarOperator/Identifier/ColumnReference/@Table)[1]', 'varchar(128)'), 19 | t.value('(ScalarOperator/Identifier/ColumnReference/@Column)[1]', 'varchar(128)'), 20 | ic.DATA_TYPE AS ConvertFrom, 21 | ic.CHARACTER_MAXIMUM_LENGTH AS ConvertFromLength, 22 | t.value('(@DataType)[1]', 'varchar(128)') AS ConvertTo, 23 | t.value('(@Length)[1]', 'int') AS ConvertToLength, 24 | query_plan 25 | FROM sys.dm_exec_cached_plans AS cp 26 | CROSS APPLY sys.dm_exec_query_plan(plan_handle) AS qp 27 | CROSS APPLY query_plan.nodes('/ShowPlanXML/BatchSequence/Batch/Statements/StmtSimple') AS batch(stmt) 28 | CROSS APPLY stmt.nodes('.//Convert[@Implicit="1"]') AS n(t) 29 | JOIN INFORMATION_SCHEMA.COLUMNS AS ic 30 | ON QUOTENAME(ic.TABLE_SCHEMA) = t.value('(ScalarOperator/Identifier/ColumnReference/@Schema)[1]', 'varchar(128)') 31 | AND QUOTENAME(ic.TABLE_NAME) = t.value('(ScalarOperator/Identifier/ColumnReference/@Table)[1]', 'varchar(128)') 32 | AND ic.COLUMN_NAME = t.value('(ScalarOperator/Identifier/ColumnReference/@Column)[1]', 'varchar(128)') 33 | WHERE t.exist('ScalarOperator/Identifier/ColumnReference[@Database=sql:variable("@dbname")][@Schema!="[sys]"]') = 1 34 | -------------------------------------------------------------------------------- /Scripts/Finding_Blocking_Queries.sql: -------------------------------------------------------------------------------- 1 | --Finding Blocking Queries 2 | --Author: Steve Stedman 3 | --One of the common problems with when diagnosing what appears to be a slow scenario where there may be blocking involved is determining what is blocking on SQL Server 4 | --This script works on SQL Server 2008, 2008R2, 2012, 2014, and 2016 5 | --If there is no blocking occurring then this query will return nothing 6 | 7 | SELECT * 8 | INTO #runningQueries 9 | FROM master..sysprocesses WITH (NOLOCK); 10 | 11 | 12 | ;WITH BlockingCTE as 13 | ( 14 | SELECT q1.blocked as spid 15 | FROM #runningQueries q1 16 | WHERE q1.blocked != 0 17 | AND q1.blocked not in (SELECT spid FROM #runningQueries q2 WHERE q2.blocked != 0) 18 | ) 19 | , recursiveBlocking AS 20 | ( 21 | SELECT b.spid, cast(0 as SMALLINT) as blocked, 22 | cast(b.spid as varchar(1000)) as treePath, 0 as level, 23 | sp1.sql_handle, b.spid as topBlock 24 | FROM BlockingCTE b 25 | INNER JOIN #runningQueries sp1 on sp1.spid = b.spid 26 | 27 | UNION ALL 28 | 29 | SELECT sp.spid, rb.spid as blocked, 30 | cast(rb.treePath + '->' + cast(sp.spid as varchar(1000)) as VARCHAR(1000)) as treePath, 31 | level + 1 as level, sp.sql_handle, topBlock 32 | FROM #runningQueries sp 33 | INNER JOIN recursiveBlocking as rb ON rb.spid = sp.blocked 34 | ) 35 | , topBlockCount AS 36 | ( 37 | SELECT *, count(1) over(partition by topBlock) as NumBlocked 38 | FROM recursiveBlocking 39 | ) 40 | SELECT DISTINCT 41 | tb.SPID, 42 | tb.blocked, 43 | tb.treePath as blockingChain, 44 | tb.level, 45 | tb.topBlock, 46 | tb.NumBlocked, 47 | LTRIM(REPLACE(REPLACE(st.text, char(10), ' '), char(13), ' ')) as theQuery 48 | FROM topBlockCount tb 49 | CROSS APPLY sys.dm_exec_sql_text(tb.sql_handle) AS st 50 | ORDER BY NumBlocked DESC, treePath 51 | OPTION (RECOMPILE); 52 | 53 | 54 | DROP TABLE #runningQueries; -------------------------------------------------------------------------------- /Scripts/Foreign_Keys_With_No_Index.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Drupal 3 | Original link: http://sqlworldwide.com/tsql-to-find-status-of-sql-server-statistics/ 4 | */ 5 | 6 | 7 | WITH fk_cte AS ( 8 | SELECT OBJECT_NAME(fk.referenced_object_id) pk_table 9 | , c2.name pk_column 10 | , kc.name pk_index_name 11 | , OBJECT_NAME(fk.parent_object_id) fk_table 12 | , c.name fk_column 13 | , fk.name fk_name 14 | , CASE WHEN i.object_id IS NOT NULL THEN 1 ELSE 0 END does_fk_has_index 15 | , i.is_primary_key is_fk_a_pk_also 16 | , i.is_unique is_index_on_fk_unique 17 | , fk.* 18 | FROM sys.foreign_keys AS fk 19 | INNER JOIN sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id 20 | INNER JOIN sys.columns AS c ON c.object_id = fk.parent_object_id AND c.column_id = fkc.parent_column_id 21 | LEFT JOIN sys.columns AS c2 ON c2.object_id = fk.referenced_object_id AND c2.column_id = fkc.referenced_column_id 22 | LEFT JOIN sys.key_constraints AS kc ON kc.parent_object_id = fk.referenced_object_id AND kc.type = 'PK' 23 | LEFT JOIN sys.index_columns AS ic ON ic.object_id = c.object_id AND ic.column_id = c.column_id 24 | LEFT JOIN sys.indexes AS i ON i.object_id = ic.object_id AND i.index_id = ic.index_id 25 | ) 26 | SELECT * FROM fk_cte 27 | LEFT JOIN sys.dm_db_partition_stats ps on ps.object_id = fk_cte.parent_object_id and ps.index_id <= 1 28 | WHERE does_fk_has_index = 0 -- and fk_table = 'LineItems' 29 | ORDER BY used_page_count DESC; 30 | -------------------------------------------------------------------------------- /Scripts/GenerateTSQLTimeSlices.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Atom 3 | Original link: http://billfellows.blogspot.ru/2017/07/generate-tsql-time-slices.html 4 | Desctiption: Generate TSQL time slices 5 | */ 6 | 7 | 8 | SELECT 9 | D.Slice AS SliceStart 10 | , LEAD 11 | ( 12 | D.Slice 13 | , 1 14 | -- Default to midnight 15 | , TIMEFROMPARTS(0,0,0,0,0) 16 | ) 17 | OVER (ORDER BY D.Slice) AS SliceStop 18 | , ROW_NUMBER() OVER (ORDER BY D.Slice) AS SliceLabel 19 | FROM 20 | ( 21 | -- Generate 15 second time slices 22 | SELECT 23 | TIMEFROMPARTS(A.rn, B.rn, C.rn, 0, 0) AS Slice 24 | FROM 25 | (SELECT TOP (24) -1 + ROW_NUMBER() OVER (ORDER BY(SELECT NULL)) FROM sys.all_objects AS AO) AS A(rn) 26 | CROSS APPLY (SELECT TOP (60) (-1 + ROW_NUMBER() OVER (ORDER BY(SELECT NULL))) FROM sys.all_objects AS AO) AS B(rn) 27 | -- 4 values since we'll aggregate to 15 seconds 28 | CROSS APPLY (SELECT TOP (4) (-1 + ROW_NUMBER() OVER (ORDER BY(SELECT NULL))) * 15 FROM sys.all_objects AS AO) AS C(rn) 29 | ) D 30 | 31 | -------------------------------------------------------------------------------- /Scripts/Generate_table_definition_to_match_query.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Created: 2017-08-21 by SQL Undercover 3 | Modified: 2019-03-26 by Konstantin Taranov 4 | Original link: https://sqlundercover.com/2017/08/21/undercover-toolbox-generate-a-temporary-table-definition-to-match-the-resultset-of-a-query/ 5 | Source link: https://github.com/ktaranov/sqlserver-kit/blob/master/Scripts/Generate_table_definition_to_match_query.sql 6 | */ 7 | 8 | SET NOCOUNT ON; 9 | 10 | DECLARE @Query VARCHAR(MAX) = 'select * from sys.databases;'; 11 | DECLARE @TempTableName VARCHAR(128) = '#temptable'; 12 | DECLARE @ColumnList VARCHAR(MAX); 13 | 14 | SELECT @ColumnList = STUFF( 15 | (SELECT ' , ' + name + ' ' + system_type_name + ' ' + 16 | CASE is_nullable 17 | WHEN 0 THEN 'NOT NULL' 18 | ELSE 'NULL' 19 | END + CHAR(10) 20 | FROM sys.dm_exec_describe_first_result_set(@Query, NULL, 0) 21 | FOR XML PATH('') 22 | ) 23 | ,1 ,1, ''); 24 | 25 | PRINT 'CREATE TABLE ' + @TempTableName + '(' 26 | PRINT @ColumnList; 27 | PRINT(');'); 28 | -------------------------------------------------------------------------------- /Scripts/Get_Amazon_RDS_Instance_Size.sql: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Get Amazon RDS Instance Size using TSQL 4 | 1 data set: InstanceSize. 5 | No 6 | Mitch Wheat 7 | 2008-07-27 8 | 2019-07-02 by Konstantin Taranov 9 | 1.0 10 | https://github.com/ktaranov/sqlserver-kit/blob/master/Scripts/Get_Amazon_RDS_Instance_Size.sql 11 | https://mitchwheat.com/2019/07/27/amazon-rds-sql-server-get-instance-size-using-tsql/ 12 | 13 | */ 14 | 15 | IF OBJECT_ID('tempdb..#AmazonErrorLog') IS NOT NULL 16 | DROP TABLE #AmazonErrorLog; 17 | 18 | CREATE TABLE #AmazonErrorLog 19 | ( 20 | LogDate datetime2, 21 | ProcessInfo nvarchar(20), 22 | [Text] nvarchar(1000) 23 | ); 24 | 25 | DECLARE @pattern nvarchar(30) = N'System Model:'; 26 | 27 | INSERT INTO #AmazonErrorLog 28 | EXEC rdsadmin.dbo.rds_read_error_log; 29 | 30 | IF @@ROWCOUNT > 0 31 | BEGIN 32 | SELECT InstanceSize = REPLACE(CAST(SUBSTRING([Text], LEN(@pattern) + 1 + PATINDEX (N'%' + @pattern + N'%', [Text]), 100), '''', '') AS varchar(100)) 33 | FROM #AmazonErrorLog 34 | WHERE PATINDEX (N'%' + @pattern + N'%', [Text]) > 0 35 | END; 36 | 37 | DROP TABLE #AmazonErrorLog; 38 | -------------------------------------------------------------------------------- /Scripts/Get_CPU_Usage_Per_Database.sql: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Get CPU Usage Per Database 4 | 1 data set with 2 columns: database name and CPUTimeAsPercentage. 5 | No 6 | Eli Leiba 7 | 2019-11-05 8 | 2019-11-05 9 | 1.0 10 | https://www.mssqltips.com/sqlservertip/6195/sql-server-function-to-measure-cpu-usage-per-database/ 11 | https://github.com/ktaranov/sqlserver-kit/blob/master/Scripts/Get_CPU_Usage_Per_Database.sql 12 | 13 | */ 14 | 15 | SELECT 16 | T.[Database] 17 | , T.CPUTimeAsPercentage 18 | FROM 19 | (SELECT 20 | [Database], 21 | CONVERT (DECIMAL (6, 3), [CPUTimeInMiliSeconds] * 1.0 / 22 | SUM ([CPUTimeInMiliSeconds]) OVER () * 100.0) AS [CPUTimeAsPercentage] 23 | FROM 24 | (SELECT 25 | dm_execplanattr.DatabaseID, 26 | DB_Name(dm_execplanattr.DatabaseID) AS [Database], 27 | SUM (dm_execquerystats.total_worker_time) AS CPUTimeInMiliSeconds 28 | FROM sys.dm_exec_query_stats dm_execquerystats 29 | CROSS APPLY 30 | (SELECT 31 | CONVERT (INT, value) AS [DatabaseID] 32 | FROM sys.dm_exec_plan_attributes(dm_execquerystats.plan_handle) 33 | WHERE attribute = N'dbid' 34 | ) dm_execplanattr 35 | GROUP BY dm_execplanattr.DatabaseID 36 | ) AS CPUPerDb 37 | ) AS T; 38 | -------------------------------------------------------------------------------- /Scripts/Get_Create_or_Alter_Index_Progress.sql: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Track progrees CREATE or ALTER Index commands 4 | 1 data set 5 | No 6 | Solomon Rutzky 7 | 2019-12-02 8 | 2019-12-02 9 | 1.0 10 | https://dba.stackexchange.com/a/139225/107045 11 | https://github.com/ktaranov/sqlserver-kit/blob/master/Scripts/Get_Create_or_Alter_Index_Progress.sql 12 | 13 | */ 14 | 15 | DECLARE @SPID int = 51; 16 | 17 | WITH agg AS 18 | ( 19 | SELECT SUM(qp.[row_count]) AS [RowsProcessed], 20 | SUM(qp.[estimate_row_count]) AS [TotalRows], 21 | MAX(qp.last_active_time) - MIN(qp.first_active_time) AS [ElapsedMS], 22 | MAX(IIF(qp.[close_time] = 0 AND qp.[first_row_time] > 0, 23 | [physical_operator_name], 24 | N'')) AS [CurrentStep] 25 | FROM sys.dm_exec_query_profiles qp 26 | WHERE qp.[physical_operator_name] IN (N'Table Scan', N'Clustered Index Scan', 27 | N'Index Scan', N'Sort') 28 | AND qp.[session_id] = @SPID 29 | ), comp AS 30 | ( 31 | SELECT *, 32 | ([TotalRows] - [RowsProcessed]) AS [RowsLeft], 33 | ([ElapsedMS] / 1000.0) AS [ElapsedSeconds] 34 | FROM agg 35 | ) 36 | SELECT [CurrentStep], 37 | [TotalRows], 38 | [RowsProcessed], 39 | [RowsLeft], 40 | CONVERT(DECIMAL(5, 2), 41 | (([RowsProcessed] * 1.0) / [TotalRows]) * 100) AS [PercentComplete], 42 | [ElapsedSeconds], 43 | (([ElapsedSeconds] / [RowsProcessed]) * [RowsLeft]) AS [EstimatedSecondsLeft], 44 | DATEADD(SECOND, 45 | (([ElapsedSeconds] / [RowsProcessed]) * [RowsLeft]), 46 | GETDATE()) AS [EstimatedCompletionTime] 47 | FROM comp; 48 | -------------------------------------------------------------------------------- /Scripts/Get_Database_Size_With_Graph.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Denis Gobo 3 | Original link: http://sqlservercode.blogspot.ru/2017/11/use-t-sql-to-create-caveman-graphs.html 4 | */ 5 | 6 | SELECT database_name = DB_NAME(database_id) 7 | , TotalSizeGB = CAST(SUM(size) * 8.0 / 1024/1024 AS DECIMAL(30,2)) 8 | , PercentSize = (CONVERT(decimal(30,4), (SUM(size) / 9 | (SELECT SUM(CONVERT(decimal(30,4),size)) 10 | FROM sys.master_files WITH(NOWAIT))) 11 | ) * 100.00) 12 | , Graph = replicate('|', ((convert(decimal(30,2), (SUM(size) / 13 | (SELECT SUM(CONVERT(decimal(30,2),size)) 14 | FROM sys.master_files WITH(NOWAIT)))) * 100) 15 | ) 16 | ) 17 | FROM sys.master_files WITH(NOWAIT) 18 | GROUP BY database_id 19 | ORDER BY PercentSize DESC; 20 | -------------------------------------------------------------------------------- /Scripts/Get_Opened_Transactions_Info.sql: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Get opened transactions information 4 | 1 data set with information about opened transactions. 5 | 2017-01-01 by Paul Randal 6 | 2020-11-19 by Konstantin Taranov 7 | 1.1 8 | https://github.com/ktaranov/sqlserver-kit/blob/master/Scripts/Get_Opened_Transactions_Info.sql 9 | https://sqlstudies.com/2013/09/05/a-t-sql-query-to-get-current-job-activity/ 10 | 11 | */ 12 | 13 | SELECT 14 | s_tst.session_id 15 | , s_es.login_name AS "Login Name" 16 | , DB_NAME (s_tdt.database_id) AS "Database" 17 | , s_tdt.database_transaction_begin_time AS "Begin Time" 18 | , s_tdt.database_transaction_log_bytes_used AS "Log Bytes" 19 | , s_tdt.database_transaction_log_bytes_reserved AS "Log Reserved Bytes" 20 | , s_est.text AS "Last T-SQL Text" 21 | , s_eqp.query_plan AS "Last Plan" 22 | FROM 23 | sys.dm_tran_database_transactions s_tdt 24 | INNER JOIN 25 | sys.dm_tran_session_transactions s_tst 26 | ON 27 | s_tst.transaction_id = s_tdt.transaction_id 28 | INNER JOIN 29 | sys.dm_exec_sessions s_es 30 | ON 31 | s_es.session_id = s_tst.session_id 32 | INNER JOIN 33 | sys.dm_exec_connections s_ec 34 | ON 35 | s_ec.session_id = s_tst.session_id 36 | LEFT OUTER JOIN 37 | sys.dm_exec_requests s_er 38 | ON 39 | s_er.session_id = s_tst.session_id 40 | CROSS APPLY 41 | sys.dm_exec_sql_text (s_ec.most_recent_sql_handle) AS s_est 42 | OUTER APPLY 43 | sys.dm_exec_query_plan (s_er.plan_handle) AS s_eqp 44 | ORDER BY 45 | s_tdt.database_transaction_begin_time ASC; 46 | GO 47 | -------------------------------------------------------------------------------- /Scripts/Get_SQLServer_Startup_Parameters.sql: -------------------------------------------------------------------------------- 1 | DECLARE @RegHive VARCHAR(50), 2 | @RegKey VARCHAR(100); 3 | 4 | SET @RegHive = 'HKEY_LOCAL_MACHINE'; 5 | SET @RegKey = 'Software\Microsoft\MSSQLSERVER\MSSQLServer\Parameters'; 6 | 7 | -- Get all of the arguments / parameters when starting up the service. 8 | DECLARE @SQLArgs TABLE ( 9 | Value VARCHAR(50), 10 | Data VARCHAR(500), 11 | ArgNum AS CONVERT(INTEGER, REPLACE(Value, 'SQLArg', ''))); 12 | 13 | INSERT INTO @SQLArgs 14 | EXECUTE master.sys.xp_instance_regenumvalues @RegHive, @RegKey; 15 | 16 | SELECT * FROM @SQLArgs; -------------------------------------------------------------------------------- /Scripts/Get_SQL_Server_Agent_Information.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Author: sqlity.net 3 | Source link: http://sqlity.net/en/1868/identify-sql-server-service-account-in-t-sql/ 4 | */ 5 | 6 | IF CAST(SERVERPROPERTY('ProductMajorVersion') AS INT) < 10 7 | BEGIN 8 | DECLARE @sn NVARCHAR(128); 9 | EXEC master.dbo.xp_regread 10 | 'HKEY_LOCAL_MACHINE', 11 | 'SYSTEM\CurrentControlSet\services\SQLSERVERAGENT', 12 | 'ObjectName', 13 | @sn OUTPUT; 14 | SELECT @sn; 15 | END; 16 | ELSE 17 | BEGIN 18 | SELECT DSS.servicename 19 | , DSS.startup_type_desc 20 | , DSS.status_desc 21 | , DSS.last_startup_time 22 | , DSS.service_account 23 | , DSS.is_clustered 24 | , DSS.cluster_nodename 25 | , DSS.filename 26 | , DSS.startup_type 27 | , DSS.status 28 | , DSS.process_id 29 | FROM sys.dm_server_services AS DSS; 30 | END; 31 | -------------------------------------------------------------------------------- /Scripts/Get_SQL_Server_Backup_Directory.sql: -------------------------------------------------------------------------------- 1 | DECLARE @HkeyLocal nvarchar(18) = N'HKEY_LOCAL_MACHINE'; 2 | DECLARE @MSSqlServerRegPath nvarchar(31) = N'SOFTWARE\Microsoft\MSSQLServer'; 3 | DECLARE @InstanceRegPath sysname = @MSSqlServerRegPath + N'\MSSQLServer'; 4 | 5 | DECLARE @BackupDirectory nvarchar(512) 6 | if 1=isnull(cast(SERVERPROPERTY('IsLocalDB') as bit), 0) 7 | SET @BackupDirectory=cast(SERVERPROPERTY('instancedefaultdatapath') as nvarchar(512)) 8 | else 9 | EXEC master.dbo.xp_instance_regread @HkeyLocal, @InstanceRegPath, N'BackupDirectory', @BackupDirectory OUTPUT; 10 | 11 | SELECT @BackupDirectory AS SQLServerBackupDirectory; 12 | -------------------------------------------------------------------------------- /Scripts/Get_Statistics_Details.sql: -------------------------------------------------------------------------------- 1 | -- Get statistics details on SQL Server 2008 R2 and higher 2 | -- Author: Kendra Little 3 | -- "This works with SQL Server 2008 R2 SP2+ / SQL Server 2012 SP1+ / All higher versions" 4 | SELECT 5 | stat.auto_created, 6 | stat.name as stats_name, 7 | STUFF((SELECT ', ' + cols.name 8 | FROM sys.stats_columns AS statcols 9 | JOIN sys.columns AS cols ON 10 | statcols.column_id=cols.column_id 11 | AND statcols.object_id=cols.object_id 12 | WHERE statcols.stats_id = stat.stats_id and 13 | statcols.object_id=stat.object_id 14 | ORDER BY statcols.stats_column_id 15 | FOR XML PATH(''), TYPE 16 | ).value('.', 'NVARCHAR(MAX)'), 1, 2, '') as stat_cols, 17 | stat.filter_definition, 18 | stat.is_temporary, 19 | stat.no_recompute, 20 | sp.last_updated, 21 | sp.modification_counter, 22 | sp.rows, 23 | sp.rows_sampled 24 | FROM sys.stats as stat 25 | CROSS APPLY sys.dm_db_stats_properties (stat.object_id, stat.stats_id) AS sp 26 | JOIN sys.objects as so on 27 | stat.object_id=so.object_id 28 | JOIN sys.schemas as sc on 29 | so.schema_id=sc.schema_id 30 | WHERE 31 | sc.name= 'Warehouse' 32 | and so.name='StockItemTransactions' 33 | ORDER BY 1, 2; 34 | GO 35 | -------------------------------------------------------------------------------- /Scripts/How_much_will_it_cost_or_save_to_rebuild_that_index.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/Scripts/How_much_will_it_cost_or_save_to_rebuild_that_index.sql -------------------------------------------------------------------------------- /Scripts/How_old_your_backups.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Tim Ford 3 | Original link: http://sqlmag.com/database-backup-and-recovery/how-old-are-your-backups 4 | */ 5 | WITH full_backups AS ( 6 | SELECT ROW_NUMBER() OVER(PARTITION BY BS.database_name, 7 | BS.type 8 | ORDER BY BS.database_name ASC, 9 | BS.backup_finish_date DESC 10 | ) AS [Row Number], 11 | D.name AS [database_name], 12 | BS.backup_set_id, 13 | BS.type AS backup_type, 14 | BS.backup_finish_date, 15 | D.recovery_model_desc 16 | FROM master.sys.databases AS D 17 | LEFT JOIN msdb.dbo.[backupset] AS BS 18 | ON D.name = BS.database_name 19 | /* FILTERING OPTIONS*/ 20 | --WHERE BS.[type] = '' 21 | --WHERE BS.[name] = '' 22 | ) 23 | SELECT FB.database_name, 24 | CASE FB.backup_type 25 | WHEN 'D' THEN 'Data' 26 | WHEN 'I' THEN 'Differential' 27 | WHEN 'L' THEN 'Transaction Log' 28 | END AS backup_type_desc, 29 | FB.recovery_model_desc, 30 | FB.backup_finish_date, 31 | BMF.physical_device_name, 32 | DATEDIFF(hour, FB.backup_finish_date, GETDATE()) AS backup_hours, 33 | DATEDIFF(minute, FB.backup_finish_date, GETDATE()) AS backup_minutes 34 | FROM full_backups FB 35 | LEFT JOIN msdb.dbo.[backupset] BS ON FB.backup_set_id = BS.backup_set_id 36 | LEFT JOIN msdb.dbo.backupmediafamily BMF ON BS.media_set_id = BMF.media_set_id 37 | WHERE FB.[Row Number] = 1 38 | ORDER BY FB.database_name, FB.[Row Number], FB.backup_type; 39 | -------------------------------------------------------------------------------- /Scripts/How_to_obtain_the_deadlocks_on_Azure.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Jose M Jurado 3 | Created Date: 2017-01-21 4 | Original link: https://blogs.msdn.microsoft.com/azuresqldbsupport/2017/01/21/lesson-learned-19-how-to-obtain-the-deadlocks-of-your-azure-sql-database/ 5 | Source link: https://github.com/ktaranov/sqlserver-kit/blob/master/Scripts/How_to_obtain_the_deadlocks_on_Azure.sql 6 | Modified: 2019-03-18 by Konstantin Taranov 7 | */ 8 | 9 | USE master; 10 | GO 11 | 12 | WITH CTE AS ( 13 | SELECT CAST(event_data AS XML) AS [target_data_XML] 14 | FROM sys.fn_xe_telemetry_blob_target_read_file('dl', null, null, null) 15 | ) 16 | SELECT target_data_XML.value('(/event/@timestamp)[1]', 'DateTime2') AS [Timestamp] 17 | , target_data_XML.query('/event/data[@name=''xml_report'']/value/deadlock') AS deadlock_xml 18 | , target_data_XML.query('/event/data[@name=''database_name'']/value').value('(/value)[1]', 'nvarchar(100)') AS [db_name] 19 | FROM CTE; 20 | -------------------------------------------------------------------------------- /Scripts/Identifying_In-Memory_Objects_When_Querying_the_Transaction_Log.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Frank Gill 3 | Original link: https://skreebydba.com/2016/07/18/identifying-in-memory-objects-when-querying-the-transaction-log/ 4 | */ 5 | 6 | 7 | SELECT 8 | f.[Current LSN], 9 | f.Operation, 10 | f.Context, 11 | f.[Transaction ID], 12 | f.operation_desc, 13 | f.tx_end_timestamp, 14 | f.total_size, 15 | OBJECT_NAME(m.object_id) AS ObjectName, 16 | f.newrow_identity, 17 | f.newrow_data, 18 | f.newrow_datasize, 19 | f.oldrow_begin_timestamp, 20 | f.oldrow_identity, 21 | f.oldrow_key_data, 22 | f.oldrow_key_datasize, 23 | f.xtp_description, 24 | f.[Log Record Fixed Length], 25 | f.[Log Record Length], 26 | f.[Flag Bits], 27 | f.[Log Reserve], 28 | f.[Log Record] 29 | FROM fn_dblog_xtp(NULL,NULL) AS f 30 | INNER JOIN sys.memory_optimized_tables_internal_attributes m 31 | ON (f.xtp_object_id - 2147483648) = (m.xtp_object_id + 2147483648) 32 | WHERE Operation LIKE '%HK%'; 33 | GO -------------------------------------------------------------------------------- /Scripts/Job_AG_Failover_Detected.sql: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Use this event to run a job when the replica becomes primary 4 | Create job to resume AG database data movement for suspended databases. 5 | 2020-08-06 by Wayne Sheffield 6 | 1.0 7 | https://github.com/ktaranov/sqlserver-kit/blob/master/Scripts/Job_AG_Failover_Detected.sql 8 | https://blog.waynesheffield.com/wayne/archive/2020/08/availability-group-issues-fixed-with-alerts/ 9 | 10 | */ 11 | 12 | /* 13 | Use this event to run a job when the replica becomes primary 14 | */ 15 | USE msdb; 16 | GO 17 | EXEC msdb.dbo.sp_add_alert @name=N'AG Failover Detected - Now Primary', 18 | @message_id=1480, 19 | @severity=0, 20 | @enabled=1, 21 | @delay_between_responses=0, 22 | @include_event_description_in=0, 23 | @event_description_keyword=N'"RESOLVING" to "PRIMARY"', 24 | @job_id=N'00000000-0000-0000-0000-000000000000'; 25 | GO 26 | /* 27 | Use this event to run a job when the replica becomes secondary 28 | */ 29 | USE msdb; 30 | GO 31 | EXEC msdb.dbo.sp_add_alert @name=N'AG Failover Detected - Now Secondary', 32 | @message_id=1480, 33 | @severity=0, 34 | @enabled=1, 35 | @delay_between_responses=0, 36 | @include_event_description_in=0, 37 | @event_description_keyword=N'"RESOLVING" to "SECONDARY"', 38 | @job_id=N'00000000-0000-0000-0000-000000000000'; 39 | GO 40 | -------------------------------------------------------------------------------- /Scripts/Jobs_Get_Runing_info.sql: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Return active jobs info. 4 | 1 data set with information about current runnig jobs. 5 | 2017-01-07 by Brenda 6 | 2020-08-10 by Konstantin Taranov 7 | 1.1 8 | https://github.com/ktaranov/sqlserver-kit/blob/master/Scripts/Jobs_Get_runing_info.sql 9 | https://sqlstudies.com/2013/09/05/a-t-sql-query-to-get-current-job-activity/ 10 | 11 | */ 12 | 13 | SELECT 14 | DISTINCT j.name as JobName 15 | , CASE WHEN ja.last_executed_step_id IS NULL THEN js.step_name ELSE js2.step_name END AS StepName 16 | , ja.start_execution_date AS StartDateTime 17 | , 'Running' AS RunStatus 18 | , RIGHT('0' + CONVERT(VARCHAR(2), DATEDIFF(second, ja.start_execution_date, GetDate())/3600), 2) + ':' + 19 | RIGHT('0' + CONVERT(VARCHAR(2), DATEDIFF(second, ja.start_execution_date, GetDate())%3600/60), 2) + ':' + 20 | RIGHT('0' + CONVERT(VARCHAR(2), DATEDIFF(second, ja.start_execution_date, GetDate())%60), 2) AS Duration 21 | , '' AS message 22 | FROM msdb.dbo.sysjobactivity ja 23 | JOIN msdb.dbo.sysjobs j 24 | ON ja.job_id = j.job_id 25 | LEFT JOIN msdb.dbo.sysjobsteps js 26 | ON j.job_id = js.job_id 27 | AND CASE WHEN ja.last_executed_step_id IS NULL THEN j.start_step_id 28 | ELSE ja.last_executed_step_id 29 | END = js.step_id 30 | LEFT JOIN msdb.dbo.sysjobsteps js2 31 | ON js.job_id = js2.job_id 32 | AND js.on_success_step_id = js2.step_id 33 | WHERE ja.session_id = ( 34 | SELECT TOP(1) session_id 35 | FROM msdb.dbo.syssessions 36 | ORDER BY agent_start_date DESC 37 | ) 38 | AND ja.start_execution_date IS NOT NULL 39 | AND ja.stop_execution_date IS NULL; 40 | -------------------------------------------------------------------------------- /Scripts/LatchStats.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Paul S. Randal 3 | Original link: http://www.sqlskills.com/blogs/paul/most-common-latch-classes-and-what-they-mean/ 4 | */ 5 | WITH [Latches] AS 6 | (SELECT 7 | [latch_class], 8 | [wait_time_ms] / 1000.0 AS [WaitS], 9 | [waiting_requests_count] AS [WaitCount], 10 | 100.0 * [wait_time_ms] / SUM ([wait_time_ms]) OVER() AS [Percentage], 11 | ROW_NUMBER() OVER(ORDER BY [wait_time_ms] DESC) AS [RowNum] 12 | FROM sys.dm_os_latch_stats 13 | WHERE [latch_class] NOT IN ( 14 | N'BUFFER') 15 | AND [wait_time_ms] > 0 16 | ) 17 | SELECT 18 | MAX ([W1].[latch_class]) AS [LatchClass], 19 | CAST (MAX ([W1].[WaitS]) AS DECIMAL(14, 2)) AS [Wait_S], 20 | MAX ([W1].[WaitCount]) AS [WaitCount], 21 | CAST (MAX ([W1].[Percentage]) AS DECIMAL(14, 2)) AS [Percentage], 22 | CAST ((MAX ([W1].[WaitS]) / MAX ([W1].[WaitCount])) AS DECIMAL (14, 4)) AS [AvgWait_S] 23 | FROM [Latches] AS [W1] 24 | INNER JOIN [Latches] AS [W2] 25 | ON [W2].[RowNum] <= [W1].[RowNum] 26 | GROUP BY [W1].[RowNum] 27 | HAVING SUM ([W2].[Percentage]) - MAX ([W1].[Percentage]) < 95; -- percentage threshold 28 | GO 29 | -------------------------------------------------------------------------------- /Scripts/Line_Of_Codes_In_database.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Pinal Dave 3 | Source link: https://blog.sqlauthority.com/2015/06/12/sql-server-how-many-line-of-code-do-you-have-in-database/ 4 | */ 5 | 6 | SELECT DB_NAME(DB_ID()) AS DBName, 7 | ObjectType, 8 | COUNT(*) AS Object_Count, 9 | SUM(LinesOfCode) AS LinesOfCode 10 | FROM (SELECT s.type AS ObjectType, 11 | LEN(definition)- LEN(REPLACE(definition,CHAR(10),'')) AS LinesOfCode, 12 | OBJECT_NAME(a.object_id) AS NameOfObject 13 | FROM sys.all_sql_modules AS a 14 | INNER JOIN sysobjects AS s 15 | ON a.object_id = s.id 16 | -- AND xtype IN('TR', 'P', 'FN', 'IF', 'TF', 'V') 17 | WHERE OBJECTPROPERTY(a.object_id,'IsMSShipped') = 0 18 | ) SubQuery 19 | GROUP BY ObjectType; 20 | -------------------------------------------------------------------------------- /Scripts/Listing_SQL_Agent_Jobs_Running_at_a_Specific_Time.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Perry Whittle 3 | Original link: http://sqlstudies.com/2013/03/01/script-to-clean-up-windows-logins-no-longer-in-ad/ 4 | */ 5 | 6 | SELECT * FROM 7 | ( 8 | SELECT JobName, RunStart, DATEADD(second, RunSeconds, RunStart) RunEnd, RunSeconds 9 | FROM 10 | ( 11 | SELECT j.name AS 'JobName', 12 | msdb.dbo.agent_datetime(run_date, run_time) AS 'RunStart', 13 | ((jh.run_duration/1000000)*86400) 14 | + (((jh.run_duration-((jh.run_duration/1000000)*1000000))/10000)*3600) 15 | + (((jh.run_duration-((jh.run_duration/10000)*10000))/100)*60) 16 | + (jh.run_duration-(jh.run_duration/100)*100) RunSeconds 17 | FROM msdb.dbo.sysjobs j 18 | INNER JOIN msdb.dbo.sysjobhistory jh ON j.job_id = jh.job_id 19 | WHERE jh.step_id=0 --The Summary Step 20 | ) AS H 21 | ) AS H2 22 | WHERE '2016-05-19 10:16:10' BETWEEN RunStart AND RunEnd 23 | ORDER BY JobName, RunEnd; 24 | -------------------------------------------------------------------------------- /Scripts/MisleadingSQLServerPerformanceCounters.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Kendra Little 3 | Original link: https://sqlworkbooks.com/2017/06/top-5-misleading-sql-server-performance-counters 4 | Desctiption: Top 5 Misleading SQL Server Performance Counters 5 | */ 6 | 7 | 8 | SELECT TOP 20 9 | (SELECT CAST(SUBSTRING(st.text, (qs.statement_start_offset/2)+1, 10 | ((CASE qs.statement_end_offset 11 | WHEN -1 THEN DATALENGTH(st.text) 12 | ELSE qs.statement_end_offset 13 | END 14 | - qs.statement_start_offset)/2) + 1) AS NVARCHAR(MAX)) FOR XML PATH(''),TYPE) AS [TSQL], 15 | qs.execution_count AS [#], 16 | qs.total_logical_reads as [logical reads], 17 | CASE WHEN execution_count = 0 THEN 0 ELSE 18 | CAST(qs.total_logical_reads / execution_count AS numeric(30,1)) 19 | END AS [avg logical reads], 20 | CAST(qs.total_worker_time/1000./1000. AS numeric(30,1)) AS [cpu sec], 21 | CASE WHEN execution_count = 0 THEN 0 ELSE 22 | CAST(qs.total_worker_time / execution_count / 1000. / 1000. AS numeric(30,1)) 23 | END AS [avg cpu sec], 24 | CAST(qs.total_elapsed_time/1000./1000. AS numeric(30,1)) AS [elapsed sec], 25 | CASE WHEN execution_count = 0 THEN 0 ELSE 26 | CAST(qs.total_elapsed_time / execution_count / 1000. / 1000. AS numeric(30,1)) 27 | END AS [avg elapsed sec], 28 | qp.query_plan AS [query execution plan] 29 | FROM sys.dm_exec_query_stats AS qs 30 | OUTER APPLY sys.dm_exec_sql_text (plan_handle) as st 31 | OUTER APPLY sys.dm_exec_query_plan (plan_handle) AS qp 32 | ORDER BY qs.total_logical_reads DESC 33 | OPTION (RECOMPILE); 34 | GO 35 | -------------------------------------------------------------------------------- /Scripts/Monitor_Deadlocks_with_Extended_Events.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/Scripts/Monitor_Deadlocks_with_Extended_Events.sql -------------------------------------------------------------------------------- /Scripts/Numbers_DATALENGTH.sql: -------------------------------------------------------------------------------- 1 | SELECT DATALENGTH(CAST(99999999999999999999999999999999999999 AS decimal(38, 0))) AS DECIMAL38 2 | , DATALENGTH(CAST( 9999999999999999999999999999 AS decimal(28, 0))) AS DECIMAL28 3 | , DATALENGTH(CAST( 9999999999999999999 AS decimal(19, 0))) AS DECIMAL19 4 | , DATALENGTH(CAST( 999999999 AS decimal( 9, 0))) AS DECIMAL9 5 | , DATALENGTH(CAST( 9 AS decimal( 1, 0))) AS DECIMAL1 6 | , DATALENGTH(CAST( 1.797693134862315807E+308 AS float(53))) AS FLOAT53 7 | , DATALENGTH(CAST( 9999999999999999999999999 AS float(25))) AS FLOAT25 8 | , DATALENGTH(CAST( 999999999999999999999999 AS float(24))) AS FLOAT24 9 | , DATALENGTH(CAST( 9 AS float( 1))) AS FLOAT1 10 | , DATALENGTH(CAST( 999999999999999999999999 AS real)) AS "REAL" 11 | , DATALENGTH(CAST( 9223372036854775807 AS bigint )) AS "BIGINT" 12 | , DATALENGTH(CAST( 2147483647 AS int )) AS "INT" 13 | , DATALENGTH(CAST( 32600 AS smallint )) AS "SMALLINT" 14 | , DATALENGTH(CAST( 255 AS tinyint )) AS "TINYINT" 15 | , DATALENGTH(CAST( 0 AS bit )) AS BIT0 16 | , DATALENGTH(CAST( 1.797693134862315807E+308 AS bit )) AS BIT1 17 | , DATALENGTH(POWER(10.0, 37)) AS "Power10^37"; 18 | -------------------------------------------------------------------------------- /Scripts/Objects_Size_In_Database.sql: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Count size in bytes veiws, triggers, procedures and function in database. 4 | 1 data set: RoutinType, SUM LENGTH of objects, SUM DATALENGTH. 5 | No 6 | Cade Roux 7 | 2008-10-20 8 | 2019-06-26 by Konstantin Taranov 9 | 1.0 10 | https://github.com/ktaranov/sqlserver-kit/blob/master/Scripts/Objects_Size_In_Database.sql 11 | https://stackoverflow.com/a/219740/2298061 12 | 13 | */ 14 | 15 | SET NOCOUNT ON; 16 | SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; 17 | 18 | WITH CTE_Routine AS ( 19 | /* Can not use INFORMATION_SCHEMA.ROUTINES because of 4000 character limit */ 20 | SELECT o.type_desc AS RoutineType 21 | , o.[name] AS RoutineName 22 | , m.[definition] AS RoutineDefinition 23 | FROM sys.sql_modules AS m 24 | INNER JOIN sys.objects AS o ON m.object_id = o.object_id 25 | ) 26 | SELECT RoutineType 27 | , SUM(LEN(RoutineDefinition)) AS RoutineLen 28 | /* DATALENGTH for counting trailing space in the end of objects definitions */ 29 | , SUM(DATALENGTH(RoutineDefinition)) / 2 AS RoutineDatalength 30 | FROM CTE_Routine 31 | GROUP BY RoutineType; 32 | -------------------------------------------------------------------------------- /Scripts/PIVOT_Columns_generator.sql: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Generate numeric columns for PIVOT statement 4 | 1 column 5 | No 6 | 2020-01-23 by Konstantin Taranov 7 | 1.0 8 | https://github.com/ktaranov/sqlserver-kit/blob/master/Scripts/PIVOT_Columns_generator.sql 9 | 10 | */ 11 | 12 | DECLARE @i int = 1990; 13 | DECLARE @s varchar(max) = ''; 14 | DECLARE @sep varchar(10) = ', '; 15 | 16 | WHILE @i <= 2020 17 | BEGIN 18 | SET @s = @s + '[' + CAST(@i AS varchar) + ']' + @sep; 19 | SET @i = @i + 1; 20 | END; 21 | 22 | SELECT LEFT(@s, DATALENGTH(@s) - DATALENGTH(@sep)) AS y; 23 | -------------------------------------------------------------------------------- /Scripts/PowerSavingCheck.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Author: bornsql 3 | Original link: https://github.com/bornsql/scripts/blob/master/power_saving_check.sql 4 | Desctiption: Create power saving check 5 | */ 6 | 7 | DECLARE @isCmdShellEnabled BIT; 8 | DECLARE @isShowAdvanced BIT; 9 | 10 | SELECT 11 | @isCmdShellEnabled = CAST(value AS BIT) 12 | FROM 13 | sys.configurations 14 | WHERE 15 | name = 'xp_cmdshell'; 16 | 17 | SELECT 18 | @isShowAdvanced = CAST(value AS BIT) 19 | FROM 20 | sys.configurations 21 | WHERE 22 | name = 'show advanced options'; 23 | 24 | IF (@isShowAdvanced = 0) 25 | BEGIN 26 | EXEC sp_configure 'show advanced options', 1; 27 | RECONFIGURE; 28 | END; 29 | 30 | IF (@isCmdShellEnabled = 0) 31 | BEGIN 32 | EXEC sp_configure 'xp_cmdshell', 1; 33 | RECONFIGURE; 34 | END; 35 | 36 | --Run xp_cmdshell to get power settings 37 | EXEC xp_cmdshell 'powercfg /list'; 38 | 39 | --Turn off 'xp_cmdshell' 40 | IF (@isCmdShellEnabled = 0) 41 | BEGIN 42 | EXEC sp_configure 'xp_cmdshell', 0; 43 | RECONFIGURE; 44 | END; 45 | 46 | --Turn off 'show advanced options' 47 | IF (@isShowAdvanced = 0) 48 | BEGIN 49 | EXEC sp_configure 'show advanced options', 0; 50 | RECONFIGURE; 51 | END; -------------------------------------------------------------------------------- /Scripts/Queries_vulnerable_to_SQL_injection.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Bert Wagner 3 | Source link: https://blog.bertwagner.com/warning-are-your-queries-vulnerable-to-sql-injection-db914fb39668 4 | */ 5 | 6 | SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; 7 | 8 | SELECT 9 | ROUTINE_CATALOG 10 | , ROUTINE_SCHEMA 11 | , ROUTINE_NAME 12 | , ROUTINE_TYPE 13 | , ROUTINE_DEFINITION 14 | FROM 15 | INFORMATION_SCHEMA.ROUTINES 16 | WHERE 17 | REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(ROUTINE_DEFINITION,CHAR(0),''),CHAR(9),''),CHAR(10),''),CHAR(11),''),CHAR(12),''),CHAR(13),''),CHAR(14),''),CHAR(160),''),' ','') 18 | LIKE '%+@%' 19 | AND 20 | ( -- Only if executes a dynamic string 21 | ROUTINE_DEFINITION LIKE '%EXEC(%' 22 | OR ROUTINE_DEFINITION LIKE '%EXECUTE%' 23 | OR ROUTINE_DEFINITION LIKE '%sp_executesql%' 24 | ); 25 | -------------------------------------------------------------------------------- /Scripts/Queries_with_parallelism.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Eitan Blumin 3 | Source link: http://www.madeiradata.com/cost-threshold-for-parallelism-and-how-to-increase-it-properly/ 4 | */ 5 | 6 | DECLARE 7 | @MinUseCount INT = 50 -- Set minimum usecount to ignore rarely-used plans 8 | , @CurrentCostThreshold FLOAT = 5 -- Serves as minimum sub-tree cost 9 | , @MaxSubTreeCost FLOAT = 30 -- Set the maximum sub-tree cost, plans with higher cost than this wouldn't normally interest us 10 | 11 | SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; 12 | 13 | SELECT @CurrentCostThreshold = CONVERT(FLOAT, value_in_use) 14 | FROM sys.configurations 15 | WHERE [name] = 'cost threshold for parallelism'; 16 | 17 | WITH XMLNAMESPACES 18 | (DEFAULT 'http://schemas.microsoft.com/sqlserver/2004/07/showplan') 19 | SELECT * 20 | FROM 21 | ( 22 | SELECT 23 | ecp.plan_handle, 24 | CompleteQueryPlan = query_plan, 25 | StatementText = n.value('(@StatementText)[1]', 'VARCHAR(4000)'), 26 | StatementSubTreeCost = n.value('(@StatementSubTreeCost)[1]', 'VARCHAR(128)'), 27 | ParallelSubTreeXML = n.query('.'), 28 | ecp.usecounts, 29 | ecp.size_in_bytes, 30 | RankPerText = ROW_NUMBER() OVER (PARTITION BY n.value('(@StatementText)[1]', 'VARCHAR(4000)') ORDER BY ecp.usecounts DESC) 31 | FROM sys.dm_exec_cached_plans AS ecp 32 | CROSS APPLY sys.dm_exec_query_plan(plan_handle) AS eqp 33 | CROSS APPLY query_plan.nodes('/ShowPlanXML/BatchSequence/Batch/Statements/StmtSimple') AS qn(n) 34 | WHERE n.query('.').exist('//RelOp[@PhysicalOp="Parallelism"]') = 1 35 | AND ecp.usecounts > @MinUseCount 36 | AND n.value('(@StatementSubTreeCost)[1]', 'float') BETWEEN @CurrentCostThreshold AND @MaxSubTreeCost 37 | ) AS Q 38 | WHERE 39 | RankPerText = 1 -- This would filter out duplicate statements, returning only those with the highest usecount 40 | ORDER BY 41 | usecounts DESC; 42 | -------------------------------------------------------------------------------- /Scripts/QueryActiveDirectory.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Ryan Adams 3 | Original link: http://www.ryanjadams.com/2016/03/query-active-directory-sql-server/ 4 | */ 5 | 6 | --There are 2 ways to query AD from SQL Server.&nbsp; The first is using OPENROWSET and the second is using OPENQUERY which requires a linked server. 7 | 8 | /*** OPENROWSET METHOD ***/ 9 | --You have to enable Ad Hoc Distributed Queries to use OPENROWSET.&nbsp; Note the OPENQUERY does NOT require this to be enabled since it uses Linked servers. 10 | 11 | sp_configure 'show advanced options', 1; 12 | RECONFIGURE; 13 | GO 14 | sp_configure 'Ad Hoc Distributed Queries', 1; 15 | RECONFIGURE; 16 | GO 17 | sp_configure 'show advanced options', 0; 18 | RECONFIGURE; 19 | GO 20 | 21 | SELECT DisplayName 22 | FROM OPENROWSET('ADSDSOOBJECT','adsdatasource','SELECT displayName 23 | FROM ''LDAP://mydomainFQDN.com/ou=mySubOU,ou=myTopOU,dc=mychilddomain,dc=myTLdomain,dc=com'' 24 | WHERE objectClass =&nbsp;''User'' ') 25 | 26 | /*** OPENQUERY METHOD ***/ 27 | --Here is where we create our Linked Server connection to AD 28 | EXEC master.dbo.sp_addlinkedserver @server = N'AD', @srvproduct=N'Active Directory Services Interface', @provider=N'ADsDSOObject', @datasrc=N'adsdatasource' 29 | GO 30 | 31 | EXEC master.dbo.sp_addlinkedsrvlogin @rmtsrvname = N'AD', @locallogin = NULL , @useself = N'True' 32 | GO 33 | 34 | --Here is the query using the above created Linked server 35 | SELECT displayName FROM OpenQuery (AD, 36 | 'SELECT displayName 37 | FROM ''LDAP://mydomainFQDN.com/ou=mySubOU,ou=myTopOU,dc=mychilddomain,dc=myTLdomain,dc=com'' 38 | WHERE objectClass =&nbsp;''User'' ') 39 | GO 40 | 41 | --Here we delete our Linked Server 42 | EXEC master.dbo.sp_dropserver @server=N'AD', @droplogins='droplogins' 43 | GO 44 | -------------------------------------------------------------------------------- /Scripts/README.md: -------------------------------------------------------------------------------- 1 | # Usefull SQL Server Scripts 2 | 3 | More than 100 useful scripts for SQL Server 4 | -------------------------------------------------------------------------------- /Scripts/Remove_Leading_and_Trailing_Backward_and_Forward_Slashes.sql: -------------------------------------------------------------------------------- 1 | /* 2 | https://sqlperformance.com/2019/10/t-sql-queries/overlooked-t-sql-gems 3 | */ 4 | 5 | SELECT string, leading_slash_count, trailing_slash_count, 6 | STUFF(STUFF(string, LEN(string) - trailing_slash_count + 1, 7 | trailing_slash_count, ''), 1, leading_slash_count, '') AS new_string 8 | FROM ( VALUES 9 | (CAST('//\\ remove leading and trailing backward (\) and forward (/) slashes \\//' AS varchar(200))), 10 | ('//\\**remove leading and trailing backward (\) and forward (/) slashes**\\//') 11 | ) AS test_data(string) 12 | CROSS APPLY ( 13 | SELECT PATINDEX('%[^/\]%', string) - 1 AS leading_slash_count, 14 | PATINDEX('%[^/\]%', REVERSE(string)) - 1 AS trailing_slash_count 15 | ) AS ca1; 16 | -------------------------------------------------------------------------------- /Scripts/RenameDefaultConstraints.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Bill Fellows 3 | Original link: http://billfellows.blogspot.ru/2017/06/rename-default-constraints.html 4 | */ 5 | -- Rename default constraints 6 | 7 | DECLARE @query nvarchar(4000); 8 | DECLARE 9 | CSR CURSOR 10 | FAST_FORWARD 11 | FOR 12 | SELECT 13 | CONCAT('ALTER TABLE ', QUOTENAME(S.name), '.', QUOTENAME(T.name), ' DROP CONSTRAINT [', DC.name, '];', CHAR(10) 14 | , 'ALTER TABLE ', QUOTENAME(S.name), '.', QUOTENAME(T.name) 15 | , ' ADD CONSTRAINT [', 'DF__', (S.name), '_', (T.name), '_', C.name, ']' 16 | , ' DEFAULT ', DC.definition, ' FOR ', QUOTENAME(C.name)) AS Query 17 | FROM 18 | sys.schemas AS S 19 | INNER JOIN 20 | sys.tables AS T 21 | ON T.schema_id = S.schema_id 22 | INNER JOIN 23 | sys.columns AS C 24 | ON C.object_id = T.object_id 25 | INNER JOIN 26 | sys.default_constraints AS DC 27 | ON DC.parent_object_id = T.object_id 28 | AND DC.object_id = C.default_object_id 29 | WHERE 30 | DC.name LIKE 'DF__%' 31 | AND DC.name <> CONCAT('DF__', (S.name), '_', (T.name), '_', C.name); 32 | 33 | OPEN CSR 34 | FETCH NEXT FROM CSR INTO @query; 35 | WHILE @@FETCH_STATUS = 0 36 | BEGIN 37 | BEGIN TRY 38 | EXECUTE sys.sp_executesql @query, N''; 39 | END TRY 40 | BEGIN CATCH 41 | PRINT ERROR_MESSAGE() 42 | PRINT @query; 43 | END CATCH 44 | FETCH NEXT FROM CSR INTO @query; 45 | END 46 | CLOSE CSR; 47 | DEALLOCATE CSR; -------------------------------------------------------------------------------- /Scripts/Reseed_Identity_Column_Value_To_Last_Value.sql: -------------------------------------------------------------------------------- 1 | /* 2 | https://eitanblumin.com/2018/11/06/re-align-identity-last-value-to-actual-max-value/ 3 | */ 4 | 5 | DECLARE @CurrTable SYSNAME, @CurrCol SYSNAME, @LastValue BIGINT 6 | DECLARE @CMD NVARCHAR(MAX), @Result NVARCHAR(MAX) 7 | 8 | DECLARE Cur CURSOR 9 | LOCAL FAST_FORWARD 10 | FOR 11 | SELECT QUOTENAME(OBJECT_SCHEMA_NAME(t.object_id)) + '.' + QUOTENAME(OBJECT_NAME(t.object_id)), c.name, CONVERT(int, c.last_value) 12 | FROM sys.identity_columns AS c 13 | INNER JOIN sys.tables AS t 14 | ON c.object_id = t.object_id 15 | WHERE c.last_value > c.seed_value 16 | 17 | OPEN Cur 18 | FETCH NEXT FROM Cur INTO @CurrTable, @CurrCol, @LastValue 19 | 20 | WHILE @@FETCH_STATUS = 0 21 | BEGIN 22 | SET @CMD = N' 23 | SELECT @pResult = N''DBCC CHECKIDENT(''''' + @CurrTable + N''''', RESEED, '' + CONVERT(nvarchar(max), MAX(' + QUOTENAME(@CurrCol) + N')) + N'') -- ' + CONVERT(nvarchar(max), @LastValue) + N''' 24 | FROM ' + @CurrTable + N' 25 | HAVING MAX(' + QUOTENAME(@CurrCol) + N') <> @LastValue' 26 | 27 | EXEC sp_executesql @CMD, N'@pResult NVARCHAR(MAX) OUTPUT, @LastValue BIGINT', @Result OUTPUT, @LastValue; 28 | 29 | IF @Result IS NOT NULL 30 | PRINT @Result; 31 | 32 | FETCH NEXT FROM Cur INTO @CurrTable, @CurrCol, @LastValue 33 | END 34 | 35 | CLOSE Cur 36 | DEALLOCATE Cur -------------------------------------------------------------------------------- /Scripts/Restore_Database_Dynamic_SQL.sql: -------------------------------------------------------------------------------- 1 | USE master; 2 | GO 3 | 4 | DECLARE @restoreStatement NVARCHAR(4000) = N''; 5 | DECLARE @databaseName SYSNAME = N'AdventureWorks2014'; 6 | DECLARE @backupFilePath NVARCHAR(2000) = N'G:\YaDisk\Backup\Distrib\SQL Server\Sample_Database\AdventureWorks\' + @databaseName + N'.bak'; 7 | DECLARE @serverPath NVARCHAR(2000) = N'K:\MSSQL\MSSQL14.MSSQLSERVER\MSSQL\DATA\'; 8 | DECLARE @debug BIT = 1; 9 | 10 | SET @restoreStatement = N' 11 | RESTORE DATABASE [@databaseName] FROM DISK = N''@backupFilePath'' 12 | WITH FILE = 1, MOVE N''@databaseName_Data'' TO N''@serverPath@databaseName_Data.mdf'', 13 | MOVE N''@databaseName_Log'' TO N''@serverPath@databaseName_Log.ldf'', NOUNLOAD, STATS = 5'; 14 | SET @restoreStatement = REPLACE(@restoreStatement, '@databaseName', @databaseName); 15 | SET @restoreStatement = REPLACE(@restoreStatement, '@backupFilePath', @backupFilePath); 16 | SET @restoreStatement = REPLACE(@restoreStatement, '@serverPath', @serverPath); 17 | 18 | IF @debug = 1 PRINT(@restoreStatement) 19 | ELSE 20 | EXEC sp_executesql @restoreStatement; 21 | GO 22 | -------------------------------------------------------------------------------- /Scripts/Run_scripts.bat: -------------------------------------------------------------------------------- 1 | REM Author: Manu Mohanan 2 | REM Original link: http://www.sqlservercentral.com/articles/SQLCMD/131634/ 3 | 4 | 5 | @@echo off 6 | 7 | del errors /f /s /q 8 | 9 | rd Errors 10 | 11 | md Errors 12 | 13 | FOR %%A IN (*.SQL) DO ( sqlcmd -S SERVERNAME -d DATABASE1 -U username -P password -i "%%A" -o "Errors\%%AError_DB1.txt" -I ) 14 | 15 | FOR %%A IN (*.SQL) DO ( sqlcmd -S SERVERNAME -d DATABASE2 -U username -P password -i "%%A" -o "Errors\%%AError_DB2.txt" -I ) 16 | -------------------------------------------------------------------------------- /Scripts/SQL Managed Instance Diagnostic Information Queries.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/Scripts/SQL Managed Instance Diagnostic Information Queries.sql -------------------------------------------------------------------------------- /Scripts/SQL Server 2005 Diagnostic Information Queries.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/Scripts/SQL Server 2005 Diagnostic Information Queries.sql -------------------------------------------------------------------------------- /Scripts/SQL Server 2008 Diagnostic Information Queries.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/Scripts/SQL Server 2008 Diagnostic Information Queries.sql -------------------------------------------------------------------------------- /Scripts/SQL Server 2008 R2 Diagnostic Information Queries.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/Scripts/SQL Server 2008 R2 Diagnostic Information Queries.sql -------------------------------------------------------------------------------- /Scripts/SQL Server 2012 Diagnostic Information Queries.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/Scripts/SQL Server 2012 Diagnostic Information Queries.sql -------------------------------------------------------------------------------- /Scripts/SQL Server 2014 Diagnostic Information Queries.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/Scripts/SQL Server 2014 Diagnostic Information Queries.sql -------------------------------------------------------------------------------- /Scripts/SQL Server 2016 Diagnostic Information Queries.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/Scripts/SQL Server 2016 Diagnostic Information Queries.sql -------------------------------------------------------------------------------- /Scripts/SQL Server 2016 SP1 Diagnostic Information Queries.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/Scripts/SQL Server 2016 SP1 Diagnostic Information Queries.sql -------------------------------------------------------------------------------- /Scripts/SQL Server 2016 SP2 Diagnostic Information Queries.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/Scripts/SQL Server 2016 SP2 Diagnostic Information Queries.sql -------------------------------------------------------------------------------- /Scripts/SQL Server 2017 Diagnostic Information Queries.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/Scripts/SQL Server 2017 Diagnostic Information Queries.sql -------------------------------------------------------------------------------- /Scripts/SQL Server 2019 Diagnostic Information Queries.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/Scripts/SQL Server 2019 Diagnostic Information Queries.sql -------------------------------------------------------------------------------- /Scripts/SQL_Azure_Approximate_Datetime_Restart.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Mitch Wheat 3 | Original link: https://mitchwheat.com/2018/10/12/when-did-my-azure-sql-database-server-restart/ 4 | Created Date: 2018-10-18 5 | Modified Date: 2018-10-18 6 | */ 7 | 8 | ;with cte as 9 | ( 10 | SELECT wait_time_ms 11 | FROM sys.dm_os_wait_stats w with(nolock) 12 | WHERE wait_type IN 13 | ( 14 | 'BROKER_TASK_STOP', 15 | 'DIRTY_PAGE_POLL', 16 | 'HADR_FILESTREAM_IOMGR_IOCOMPLETION', 17 | 'LAZYWRITER_SLEEP', 18 | 'LOGMGR_QUEUE', 19 | 'REQUEST_FOR_DEADLOCK_SEARCH', 20 | 'XE_DISPATCHER_WAIT', 21 | 'XE_TIMER_EVENT' 22 | ) 23 | ) 24 | select 25 | approx_ms_since_restart = AVG(wait_time_ms), 26 | approximate_restart_date = DATEADD(s, AVG(-wait_time_ms)/1000, GETDATE()) 27 | from 28 | cte 29 | cross join 30 | (select 31 | q1 = min(wait_time_ms), 32 | q3 = max(wait_time_ms), 33 | iqr = max(wait_time_ms) - min(wait_time_ms) 34 | from (select 35 | wait_time_ms, 36 | row_number() over (order by wait_time_ms) as seqnum, 37 | count(*) over (partition by null) as total 38 | from cte 39 | ) t 40 | where seqnum = cast(total * 0.25 as int) or seqnum = cast(total * 0.75 as int) 41 | ) qts 42 | where (wait_time_ms >= q1 - 1.5 * iqr) AND (wait_time_ms <= q3 + 1.5 * iqr); 43 | -------------------------------------------------------------------------------- /Scripts/SQL_Server_Fixed_Role_Permissions.sql: -------------------------------------------------------------------------------- 1 | --SQL Server Fixed Role Permissions 2 | --Author: Jason Brimhall 3 | --In this script, I have taken the results from each of the stored procedures and dumped them into a temp table. 4 | --Using this temp table, I can now join to this table to get a more complete list of the permissions in effect for various principals. 5 | 6 | CREATE TABLE #role_permission 7 | ( 8 | DBFixedRole VARCHAR(128) 9 | , Permission VARCHAR(128) 10 | ) 11 | INSERT INTO #role_permission 12 | ( DBFixedRole, Permission ) 13 | EXECUTE sp_dbfixedrolepermission 14 | GO 15 | 16 | INSERT INTO #role_permission 17 | ( DBFixedRole, Permission ) 18 | EXECUTE sp_srvrolepermission 19 | GO 20 | 21 | SELECT * 22 | FROM #role_permission r; 23 | 24 | DROP TABLE #role_permission; -------------------------------------------------------------------------------- /Scripts/Suspect_Database_Pages.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Ben Snaidero 3 | Original link: https://www.mssqltips.com/sqlservertip/4166/automate-alerting-for-sql-server-suspect-database-pages/ 4 | */ 5 | 6 | SELECT sp.database_id AS DatabaseID 7 | , d.name AS DatabaseName 8 | , sp.file_id AS FileID 9 | , mf.physical_name AS FileName 10 | , sp.page_id AS PageID 11 | , CASE 12 | WHEN sp.event_type = 1 13 | THEN '823 or 824 error other than a bad checksum or a torn page' 14 | WHEN sp.event_type = 2 15 | THEN 'Bad checksum' 16 | WHEN sp.event_type = 3 17 | THEN 'Torn Page' 18 | WHEN sp.event_type = 4 19 | THEN 'Restored (The page was restored after it was marked bad)' 20 | WHEN sp.event_type = 5 21 | THEN 'Repaired (DBCC repaired the page)' 22 | WHEN sp.event_type = 7 23 | THEN 'Deallocated by DBCC' 24 | END AS EventDesc 25 | , sp.error_count AS ErrorCount 26 | , sp.last_update_date AS LastUpdated 27 | FROM msdb.dbo.suspect_pages AS sp 28 | INNER JOIN sys.databases AS d ON d.database_id = sp.database_id 29 | INNER JOIN sys.master_files AS mf ON mf.database_id = sp.database_id AND mf.file_id = sp.file_id; 30 | -------------------------------------------------------------------------------- /Scripts/Table_Count_Fast_Alternatives.sql: -------------------------------------------------------------------------------- 1 | -- source: http://www.brentozar.com/archive/2014/02/count-number-rows-table-sql-server/ 2 | DECLARE @TableName sysname = N'bigTransactionHistory'; 3 | 4 | SELECT TBL.object_id 5 | , TBL.name 6 | , SUM(PART.rows) AS NumberOfRows 7 | FROM sys.tables AS TBL 8 | INNER JOIN sys.partitions AS PART ON TBL.object_id = PART.object_id 9 | INNER JOIN sys.indexes AS IDX ON PART.object_id = IDX.object_id 10 | AND PART.index_id = IDX.index_id 11 | WHERE TBL.name = @TableName 12 | AND IDX.index_id < 2 13 | GROUP BY TBL.object_id, TBL.name; 14 | 15 | 16 | DECLARE @tableName sysname = N'bigTransactionHistory'; 17 | 18 | SELECT object_id 19 | , SCHEMA_NAME(object_id) AS SchemaName 20 | , OBJECT_NAME(object_id) AS TableName 21 | , SUM(row_count) AS NumberOfRows 22 | FROM sys.dm_db_partition_stats 23 | WHERE object_id = OBJECT_ID(@tableName) AND index_id < 2 24 | GROUP BY object_id 25 | , SCHEMA_NAME(object_id) 26 | , OBJECT_NAME(object_id); 27 | -------------------------------------------------------------------------------- /Scripts/Tempdb_Contention.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Paul Randal 3 | Original link: http://www.sqlskills.com/blogs/paul/the-accidental-dba-day-27-of-30-troubleshooting-tempdb-contention/ 4 | */ 5 | 6 | SELECT 7 | [owt].[session_id], 8 | [owt].[exec_context_id], 9 | [owt].[wait_duration_ms], 10 | [owt].[wait_type], 11 | [owt].[blocking_session_id], 12 | [owt].[resource_description], 13 | CASE [owt].[wait_type] 14 | WHEN N'CXPACKET' THEN 15 | RIGHT ([owt].[resource_description], 16 | CHARINDEX (N'=', REVERSE ([owt].[resource_description])) - 1) 17 | ELSE NULL 18 | END AS [Node ID], 19 | [es].[program_name], 20 | [est].text, 21 | [er].[database_id], 22 | [eqp].[query_plan], 23 | [er].[cpu_time] 24 | FROM sys.dm_os_waiting_tasks [owt] 25 | INNER JOIN sys.dm_exec_sessions [es] ON 26 | [owt].[session_id] = [es].[session_id] 27 | INNER JOIN sys.dm_exec_requests [er] ON 28 | [es].[session_id] = [er].[session_id] 29 | OUTER APPLY sys.dm_exec_sql_text ([er].[sql_handle]) [est] 30 | OUTER APPLY sys.dm_exec_query_plan ([er].[plan_handle]) [eqp] 31 | WHERE 32 | [es].[is_user_process] = 1 33 | ORDER BY 34 | [owt].[session_id], 35 | [owt].[exec_context_id]; 36 | GO -------------------------------------------------------------------------------- /Scripts/Trace_Flag/Trace_Flag_460.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/Scripts/Trace_Flag/Trace_Flag_460.sql -------------------------------------------------------------------------------- /Scripts/Trace_Flag/Trace_Flag_8726.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Trace Flag Demo: 8726 3 | !!! Undocumented trace flag !!! 4 | Function: Disables the heuristic that discourages the optimizer from producing an index union plan. 5 | SQL Server Version: ? 6 | Information link: https://github.com/ktaranov/sqlserver-kit/blob/master/SQL%20Server%20Trace%20Flag.md#8726 7 | */ 8 | 9 | USE StackOverflow2010; 10 | GO 11 | 12 | /* Execution Plan: https://www.brentozar.com/pastetheplan/?id=B1mSzXGv8 */ 13 | /* No index union (seek on Users, multiple scans on Comments) */ 14 | SELECT * 15 | FROM Users u 16 | LEFT JOIN Comments c 17 | ON u.Id = c.UserId 18 | OR u.Id = c.PostId 19 | WHERE u.DisplayName = 'alex'; 20 | 21 | /* Gets the index union plan */ 22 | SELECT * 23 | FROM Users u 24 | LEFT JOIN Comments c 25 | ON u.Id = c.UserId 26 | OR u.Id = c.PostId 27 | WHERE u.DisplayName = 'alex' 28 | OPTION (QUERYTRACEON 8726); 29 | -------------------------------------------------------------------------------- /Scripts/Trace_Flag/Trace_Flag_8727.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Trace Flag Demo: 8727 3 | !!! Undocumented trace flag !!! 4 | Function: Can be used to prevent unwanted index union plans. 5 | SQL Server Version: ? 6 | Information link: https://github.com/ktaranov/sqlserver-kit/blob/master/SQL%20Server%20Trace%20Flag.md#8727 7 | */ 8 | 9 | USE StackOverflow2010; 10 | GO 11 | 12 | /* Execution Plan: https://www.brentozar.com/pastetheplan/?id=HkwhlQGwL */ 13 | /* Gets an index union plan normally */ 14 | SELECT * 15 | FROM dbo.Users u 16 | OUTER APPLY 17 | ( 18 | SELECT * 19 | FROM dbo.Comments c 20 | WHERE 21 | u.Id = c.UserId 22 | OR u.Id = c.PostId 23 | ) c 24 | WHERE u.DisplayName = 'alex'; 25 | 26 | /* No index union (seek on Users, multiple scans on Comments) */ 27 | SELECT * 28 | FROM dbo.Users u 29 | OUTER APPLY 30 | ( 31 | SELECT * 32 | FROM dbo.Comments c 33 | WHERE 34 | u.Id = c.UserId 35 | OR u.Id = c.PostId 36 | ) c 37 | WHERE u.DisplayName = 'alex' 38 | OPTION (QUERYTRACEON 8727); 39 | -------------------------------------------------------------------------------- /Scripts/Truncate log file.sql: -------------------------------------------------------------------------------- 1 | ALTER DATABASE DATABASENAME SET RECOVERY SIMPLE; 2 | DBCC SHRINKFILE (DATABASENAME_log, 1, TRUNCATEONLY); 3 | ALTER DATABASE DATABASENAME SET RECOVERY FULL; -------------------------------------------------------------------------------- /Scripts/Using_OPENROWSET_to_Query_Excel.sql: -------------------------------------------------------------------------------- 1 | /* 2 | https://www.mssqltips.com/sqlservertip/6178/read-excel-file-in-sql-server-with-openrowset-or-opendatasource/ 3 | */ 4 | 5 | CREATE TABLE #Provider ( 6 | ProviderName varchar(100) NOT NULL 7 | , [ParseName] varchar(100) NOT NULL 8 | , ProviderDescription varchar(100) NOT NULL 9 | ); 10 | 11 | INSERT INTO #Provider EXEC sys.sp_enum_oledb_providers; 12 | 13 | IF NOT EXISTS (SELECT 1 FROM #Provider WHERE ProviderName LIKE 'Microsoft.ACE.OLEDB%') 14 | PRINT('Please install Microsoft.ACE.OLEDB driver: 16 - https://www.microsoft.com/en-us/download/details.aspx?id=54920 or 12 - https://www.microsoft.com/en-US/download/details.aspx?id=13255'); 15 | ELSE PRINT('Microsoft.ACE.OLEDB is installed. Go next.'); 16 | 17 | IF (SELECT "value" FROM sys.configurations WHERE "name" = 'Ad Hoc Distributed Queries') <> 1 18 | BEGIN 19 | EXEC sp_configure 'show advanced option', '1'; 20 | RECONFIGURE; 21 | EXEC sp_configure 'Ad Hoc Distributed Queries', 1; 22 | RECONFIGURE; 23 | END; 24 | 25 | EXEC master.[sys].[sp_MSset_oledb_prop] N'Microsoft.ACE.OLEDB.16.0', N'AllowInProcess', 0; 26 | 27 | SELECT * 28 | FROM OPENROWSET( 29 | 'Microsoft.ACE.OLEDB.16.0' 30 | , 'Excel 12.0;Database=g:\MSSQL17\Instagram_Statistics.xlsx' 31 | , 'SELECT * FROM [decoupagpro$]') AS op; 32 | -------------------------------------------------------------------------------- /Scripts/Visualizing_VLF.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Steve Stedman 3 | Original link: http://stevestedman.com/2016/10/visualizing-vlfs-updated/ 4 | */ 5 | 6 | DECLARE @logInfoResults AS TABLE 7 | ( 8 | [RecoveryUnitId] BIGINT, -- only on SQL Server 2012 and newer 9 | [FileId] TINYINT, 10 | [FileSize] BIGINT, 11 | [StartOffset] BIGINT, 12 | [FSeqNo] INTEGER, 13 | [Status] TINYINT, 14 | [Parity] TINYINT, 15 | [CreateLSN] NUMERIC(38,0) 16 | ); 17 | 18 | INSERT INTO @logInfoResults 19 | EXEC sp_executesql N'DBCC LOGINFO WITH NO_INFOMSGS'; 20 | 21 | SELECT cast(FileSize / 1024.0 / 1024 AS DECIMAL(20,1)) as FileSizeInMB 22 | , CASE WHEN FSeqNo = 0 THEN 'Available - Never Used' 23 | ELSE (CASE WHEN [Status] = 2 THEN 'In Use' ELSE 'Available' END) 24 | END AS TextStatus 25 | , [Status] 26 | , REPLICATE('x', FileSize / MIN(FileSize) over()) as [BarChart ________________________________________________________________________________________________] 27 | FROM @logInfoResults; 28 | GO 29 | -------------------------------------------------------------------------------- /Scripts/When_SQL_Server_Was_Installed.sql: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | When SQL Server Was Installed. 4 | Find in sys.server_principals oldest NT Service login. 5 | No 6 | Rebecca Lewis 7 | 2019-04-25 8 | 2019-04-30 by Konstantin Taranov 9 | 1.0 10 | https://github.com/ktaranov/sqlserver-kit/blob/master/Scripts/When_SQL_Server_Was_Installed.sql 11 | 12 | */ 13 | 14 | 15 | SELECT TOP(1) 16 | SERVERPROPERTY('ProductVersion') AS ProductVersion 17 | , SERVERPROPERTY('ProductLevel') AS ProductLevel 18 | , SERVERPROPERTY('Edition') AS Edition 19 | , SERVERPROPERTY('MachineName') AS MachineName 20 | , create_date AS "SQL Server Installation Date" 21 | , name AS SystemUserName 22 | FROM sys.server_principals 23 | WHERE name LIKE 'NT Service%' 24 | ORDER BY create_date; 25 | -------------------------------------------------------------------------------- /Scripts/Which_Indexes_are_not_Used.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Greg Larsen 3 | Original links: http://www.databasejournal.com/features/mssql/which-indexes-are-not-used.html 4 | */ 5 | 6 | SELECT o.name Object_Name, 7 | SCHEMA_NAME(o.schema_id) Schema_name, 8 | i.name Index_name, 9 | i.Type_Desc, 10 | CASE WHEN (s.user_seeks > 0 11 | OR s.user_scans > 0 12 | OR s.user_lookups > 0) 13 | AND s.user_updates > 0 14 | THEN 'USED AND UPDATED' 15 | WHEN (s.user_seeks > 0 16 | OR s.user_scans > 0 17 | OR s.user_lookups > 0) 18 | AND s.user_updates = 0 19 | THEN 'USED AND NOT UPDATED' 20 | WHEN s.user_seeks IS NULL 21 | AND s.user_scans IS NULL 22 | AND s.user_lookups IS NULL 23 | AND s.user_updates IS NULL 24 | THEN 'NOT USED AND NOT UPDATED' 25 | WHEN (s.user_seeks = 0 26 | AND s.user_scans = 0 27 | AND s.user_lookups = 0) 28 | AND s.user_updates > 0 29 | THEN 'NOT USED AND UPDATED' 30 | ELSE 'NONE OF THE ABOVE' 31 | END AS Usage_Info, 32 | COALESCE(s.user_seeks,0) AS user_seeks, 33 | COALESCE(s.user_scans,0) AS user_scans, 34 | COALESCE(s.user_lookups,0) AS user_lookups, 35 | COALESCE(s.user_updates,0) AS user_updates 36 | FROM sys.objects AS o 37 | JOIN sys.indexes AS i 38 | ON o.object_id = i.object_id 39 | LEFT OUTER JOIN 40 | sys.dm_db_index_usage_stats AS s 41 | ON i.object_id = s.object_id 42 | AND i.index_id = s.index_id 43 | WHERE o.type = 'U' 44 | -- Clustered and Non-Clustered indexes 45 | AND i.type IN (1, 2) 46 | ORDER BY user_seeks, user_scans, user_lookups, user_updates ASC; -------------------------------------------------------------------------------- /Scripts/WhiteListIPTable.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Patrick Keisler 3 | Original link: http://www.patrickkeisler.com/2017/05/create-whitelist-for-sql-server-updated.html 4 | */ 5 | 6 | USE master; 7 | GO 8 | 9 | IF OBJECT_ID('dbo.WhiteList') IS NOT NULL 10 | DROP TABLE dbo.WhiteList; 11 | GO 12 | 13 | CREATE TABLE dbo.WhiteList 14 | ( 15 | Id INT IDENTITY(1,1) PRIMARY KEY 16 | ,LoginName VARCHAR(255) 17 | ,HostName VARCHAR(255) 18 | ,HostIpAddress VARCHAR(50) 19 | ,Comments VARCHAR(2000) 20 | ); 21 | GO 22 | 23 | GRANT SELECT ON dbo.WhiteList TO PUBLIC; 24 | GO 25 | 26 | INSERT dbo.WhiteList(LoginName,HostName,HostIpAddress,Comments) 27 | VALUES 28 | ('*','ECHOBASE1','*','Any user from the workstation "ECHOBASE1" is allowed to connect, regardless of IP address.') 29 | ,('WebSiteLogin','webserver1','192.168.100.55','Only the WebSiteLogin from webserver1 with an IP of 192.168.100.55 is allowed access.'); 30 | GO 31 | 32 | CREATE TRIGGER WhiteListTrigger 33 | ON ALL SERVER FOR LOGON 34 | AS 35 | BEGIN 36 | DECLARE 37 | @LoginName VARCHAR(255) = ORIGINAL_LOGIN() 38 | ,@HostName VARCHAR(255) = HOST_NAME() 39 | ,@HostIpAddress VARCHAR(50) = CONVERT(VARCHAR(50),CONNECTIONPROPERTY('client_net_address')); 40 | 41 | IF 42 | ( 43 | SELECT COUNT(*) FROM dbo.WhiteList 44 | WHERE 45 | ( 46 | (LoginName = @LoginName) OR (LoginName = '*') 47 | ) 48 | AND 49 | ( 50 | (HostName = @HostName) OR (HostName = '*') 51 | ) 52 | AND 53 | ( 54 | (HostIpAddress = @HostIpAddress) OR (HostIpAddress = '*') 55 | ) 56 | ) = 0 57 | ROLLBACK; 58 | END; 59 | GO 60 | -------------------------------------------------------------------------------- /Scripts/Who_dropped_altered_database_object.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Created: 2018-10-31 by Rebecca Lewis 3 | Modified: 2019-03-26 by Konstantin Taranov 4 | Original link: http://www.sqlfingers.com/2018/10/who-dropped-that-table.html 5 | Source link: https://github.com/ktaranov/sqlserver-kit/blob/master/Scripts/Who_dropped_altered_database_object.sql 6 | */ 7 | 8 | SET NOCOUNT ON; 9 | 10 | DECLARE @current NVARCHAR(255); 11 | DECLARE @start NVARCHAR(255); 12 | DECLARE @index INT; 13 | 14 | /* find your trace path */ 15 | SELECT @current = path FROM sys.traces WHERE is_default = 1; 16 | 17 | SET @current = REVERSE(@current); 18 | SET @index = PATINDEX('%\%', @current); 19 | SET @current = REVERSE(@current); 20 | SET @start = LEFT(@current, LEN(@current) - @index) + N'\log.trc'; 21 | 22 | /* query on the eventclasses for delete and alter */ 23 | SELECT te.name AS EventName 24 | , gt.DatabaseName 25 | , gt.ObjectName 26 | , gt.StartTime 27 | , gt.EndTime 28 | , gt.HostName 29 | , gt.ApplicationName 30 | , gt.NTUserName 31 | , gt.NTDomainName 32 | , gt.LoginName 33 | , gt.SPID 34 | , gt.EventClass 35 | , gt.EventSubClass 36 | , gt.TextData 37 | , gt.FileName 38 | , gt.IsSystem 39 | FROM fn_trace_gettable(@start, DEFAULT) AS gt 40 | LEFT JOIN sys.trace_events AS te ON gt.EventClass = te.trace_event_id 41 | WHERE gt.EventSubClass = 0 42 | AND gt.DatabaseID <> 2 /* tempdb */ 43 | /* 44 | AND EventClass IN ( 164 /* Object:Deleted */ 45 | , 47 /* Object:Altered */ 46 | , 46 /* Object:Created */ 47 | ) 48 | */ 49 | ORDER BY gt.StartTime; 50 | -------------------------------------------------------------------------------- /Scripts/Windows logins not in AD.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Perry Whittle 3 | Original link: http://sqlstudies.com/2013/03/01/script-to-clean-up-windows-logins-no-longer-in-ad/ 4 | */ 5 | 6 | IF (OBJECT_ID(‘tempdb..#invalidlogins’) IS NOT NULL) 7 | BEGIN 8 | DROP TABLE #invalidlogins; 9 | END 10 | 11 | CREATE TABLE #invalidlogins( 12 | perr ACCTSID VARBINARY(85) 13 | , NTLOGIN SYSNAME); 14 | 15 | INSERT INTO #invalidlogins 16 | EXEC sys.sp_validatelogins; 17 | 18 | SELECT NTLOGIN FROM #invalidlogins 19 | ORDER BY 1; 20 | -------------------------------------------------------------------------------- /Scripts/glen_berry_diagnostic_queries_links.txt: -------------------------------------------------------------------------------- 1 | https://www.dropbox.com/s/k1vauzxxhyh1fnb/SQL%20Server%202019%20Diagnostic%20Information%20Queries.sql?dl=1 2 | https://www.dropbox.com/s/3ix2lqhry34c5wy/SQL%20Server%202017%20Diagnostic%20Information%20Queries.sql?dl=1 3 | https://www.dropbox.com/s/pkpxihdkq3odgbj/SQL%20Server%202016%20SP2%20Diagnostic%20Information%20Queries.sql?dl=1 4 | https://www.dropbox.com/s/w6gi8j76k64fgbg/SQL%20Server%202016%20SP1%20Diagnostic%20Information%20Queries.sql?dl=1 5 | https://www.dropbox.com/s/uttp0843e5078vs/SQL%20Server%202014%20Diagnostic%20Information%20Queries.sql?dl=1 6 | https://www.dropbox.com/s/3l4yotzedk45xeh/SQL%20Server%202012%20Diagnostic%20Information%20Queries.sql?dl=1 7 | https://www.dropbox.com/s/fq6hyw899fe3crv/SQL%20Server%202008%20R2%20Diagnostic%20Information%20Queries.sql?dl=1 8 | https://www.dropbox.com/s/mjxw1w9tgw7eo6g/SQL%20Server%202008%20Diagnostic%20Information%20Queries.sql?dl=1 9 | https://www.dropbox.com/s/3kkskuheyzauih9/SQL%20Server%202005%20Diagnostic%20Information%20Queries.sql?dl=1 10 | -------------------------------------------------------------------------------- /Solution/BaselineCollector/README.md: -------------------------------------------------------------------------------- 1 | # Microsoft SQL Server Base Line Collector Solution 2 | Comprehensive Baseline Collecting Solution 3 | 4 | Original link: http://www.sqlapprentice.net/category/baseline/ 5 | Author: Robert Virag 6 | -------------------------------------------------------------------------------- /Solution/Ola_Maintenance_Solution/CommandLog.sql: -------------------------------------------------------------------------------- 1 | SET ANSI_NULLS ON 2 | GO 3 | SET QUOTED_IDENTIFIER ON 4 | GO 5 | SET ANSI_PADDING ON 6 | GO 7 | CREATE TABLE [dbo].[CommandLog]( 8 | [ID] int IDENTITY(1,1) NOT NULL CONSTRAINT [PK_CommandLog] PRIMARY KEY CLUSTERED, 9 | [DatabaseName] sysname NULL, 10 | [SchemaName] sysname NULL, 11 | [ObjectName] sysname NULL, 12 | [ObjectType] char(2) NULL, 13 | [IndexName] sysname NULL, 14 | [IndexType] tinyint NULL, 15 | [StatisticsName] sysname NULL, 16 | [PartitionNumber] int NULL, 17 | [ExtendedInfo] xml NULL, 18 | [Command] nvarchar(max) NOT NULL, 19 | [CommandType] nvarchar(60) NOT NULL, 20 | [StartTime] datetime NOT NULL, 21 | [EndTime] datetime NULL, 22 | [ErrorNumber] int NULL, 23 | [ErrorMessage] nvarchar(max) NULL 24 | ) 25 | GO 26 | -------------------------------------------------------------------------------- /Solution/README.md: -------------------------------------------------------------------------------- 1 | # Microsoft SQL Server Solutions 2 | 3 | - [dbWarden](/Solution/dbWarden) a free SQL Server Monitoring Package (by Stevie Rounds and Michael Rounds) 4 | - [Base line Collector script](/Solution/BaselineCollector) (by Robert Virag) 5 | - [Ola Maintenance Solution](/Solution/Ola_Maintenance_Solution) (by Ola Hallengren) 6 | - [SysJobHistory](/Solution/SysJobHistory) (by David Wentzel) 7 | -------------------------------------------------------------------------------- /Solution/SysJobHistory/DBA_sysjobhistory_config_tbl.sql: -------------------------------------------------------------------------------- 1 | IF NOT EXISTS (select * from sys.objects WHERE name = 'DBA_sysjobhistory_config') 2 | BEGIN 3 | CREATE TABLE DBA_sysjobhistory_config ( 4 | JobName varchar(256), --(name of the job for this retention setting) 5 | CategoryName varchar(256), --(only JobName or CategoryName should be completed) 6 | NumDaysToRetain int , --(number of days to retain for this entry) 7 | NumFailureDaysToRetain int --(number of days to retain for failure entries) 8 | ); 9 | END 10 | GO 11 | 12 | IF EXISTS (select * from sys.objects WHERE name = 'v_sysjobs') 13 | BEGIN 14 | DROP VIEW v_sysjobs 15 | END; 16 | GO 17 | CREATE VIEW v_sysjobs 18 | AS 19 | SELECT 20 | CASE c.category_id WHEN 0 THEN NULL ELSE c.name END AS CategoryName, 21 | j.job_id AS job_id, 22 | j.name AS JobName 23 | FROM msdb..sysjobs j 24 | JOIN msdb..syscategories c 25 | ON j.category_id = c.category_id 26 | GO 27 | 28 | 29 | IF EXISTS (select * from sys.objects WHERE name = 'v_sysjobhistory') 30 | BEGIN 31 | DROP VIEW v_sysjobhistory 32 | END; 33 | GO 34 | CREATE VIEW v_sysjobhistory 35 | AS 36 | SELECT 37 | instance_id, 38 | job_id, 39 | run_date, 40 | run_time, 41 | run_status 42 | FROM msdb..sysjobhistory 43 | GO 44 | 45 | 46 | -------------------------------------------------------------------------------- /Solution/SysJobHistory/DBA_sysjobhistory_driver.sql: -------------------------------------------------------------------------------- 1 | if exists (select * from sysobjects where id = object_id('DBA_sysjobhistory_driver') and sysstat & 0xf = 4) 2 | DROP procedure dbo.DBA_sysjobhistory_driver 3 | GO 4 | 5 | 6 | CREATE PROCEDURE DBA_sysjobhistory_driver 7 | AS 8 | BEGIN 9 | SET DEADLOCK_PRIORITY LOW 10 | DECLARE @job_id uniqueidentifier 11 | 12 | SET NOCOUNT ON 13 | 14 | --first, blindly set SQLAgent sysjobhistory to unlimited. This shuts off sp_jobhistory_row_limiter 15 | --which cuts down on waits and job blocking for larger customers. 16 | EXEC msdb.dbo.sp_set_sqlagent_properties @jobhistory_max_rows=-1, 17 | @jobhistory_max_rows_per_job=-1 18 | 19 | 20 | DECLARE CURSER CURSOR FOR 21 | SELECT job_id 22 | FROM v_sysjobs 23 | OPEN CURSER 24 | FETCH NEXT FROM CURSER INTO @job_id 25 | WHILE (@@FETCH_STATUS = 0) 26 | BEGIN 27 | --PRINT 'Running DBA_PM_sp_jobhistory_row_limiter for @job_id: ' + convert(varchar(200),@job_id) 28 | EXEC DBA_sp_jobhistory_row_limiter @job_id = @job_id 29 | FETCH NEXT FROM CURSER INTO @job_id 30 | END 31 | CLOSE CURSER 32 | DEALLOCATE CURSER 33 | 34 | 35 | 36 | END -------------------------------------------------------------------------------- /Solution/SysJobHistory/README.md: -------------------------------------------------------------------------------- 1 | # Microsoft SQL Server sysjobhistory solution 2 | 3 | Original link: http://git.davewentzel.com/dwentzel/sqlscripts/tree/master/sysjobhistoryPurge 4 | Author: David Wentzel 5 | 6 | A utility that customizes what gets purged via sysjobhistory. 7 | 8 | Allows far more flexibility than what Microsoft provides natively. Also, the purge is "smart" and will not cause blocking and concurrency problems on instances with many, frequent SQL Agent jobs. Includes tsqlt unit tests. 9 | 10 | `seeddata.sql` is the only file that should need to be customized. You place your jobs and categories and their custom retention settings here. 11 | 12 | `DBA_sysjobhistory_config_tbl.sql` builds the table that handles the custom sysjobhistory retention configuration. 13 | 14 | `DBA_sysjobhistory_driver.sql` configures SQL Agent for unlimited history retention, since we'll be handling that now. It then examines each job in turn and runs `DBA_sp_jobhistory_row_limiter` to retain the custom settings for this job/category. This procedure should be scheduled to run every day (or so, depending on your requirements). 15 | 16 | `DBA_sp_jobhistory_row_limiter.sql` is more or less a copy of MS-provided sp_jobhistory_row_limiter with our custom logic. 17 | 18 | `DBA_sysjobhistory_driver_Tests.sql` is the tsqlt unit tests for this feature. 19 | -------------------------------------------------------------------------------- /Solution/SysJobHistory/seeddata.sql: -------------------------------------------------------------------------------- 1 | IF NOT EXISTS (select * from DBA_PM_sysjobhistory_config) 2 | BEGIN 3 | --insert base seed data, but only if this is the first run of SFU installer 4 | INSERT INTO DBA_sysjobhistory_config VALUES (NULL,'ETL',1,90) 5 | INSERT INTO DBA_sysjobhistory_config VALUES ('(default)','(default)',3,90) 6 | INSERT INTO DBA_sysjobhistory_config VALUES (NULL,'SFU TOOL',1,90) 7 | END; 8 | -------------------------------------------------------------------------------- /Solution/dbWarden/README.md: -------------------------------------------------------------------------------- 1 | # Microsoft SQL Server dbWarden Solution 2 | 3 | Original link: http://www.sqlservercentral.com/articles/Monitoring/98106/ 4 | Author: Michael Rounds 5 | 6 | This script creates a dbWarden database and all objects necessary to setup a database monitoring and alerting solution that notifies via email/texting. 7 | -------------------------------------------------------------------------------- /Stored_Procedure/Recover_Deleted_Data_Proc.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/Stored_Procedure/Recover_Deleted_Data_Proc.sql -------------------------------------------------------------------------------- /Stored_Procedure/dbo.sp_Defrag_Indexes.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/Stored_Procedure/dbo.sp_Defrag_Indexes.sql -------------------------------------------------------------------------------- /Stored_Procedure/dbo.sp_Example_RegisterAssembly_PDFCLR.sql: -------------------------------------------------------------------------------- 1 | CREATE PROCEDURE dbo.spExample_RegisterAssembly_PDFCLR 2 | AS 3 | BEGIN 4 | DECLARE @FilePath varchar(1024) 5 | SET @FilePath = 'c:\ServerEnvironment\' 6 | 7 | CREATE TABLE #References (AssemblyName sysname, FQFileName varchar(1024)) 8 | INSERT INTO #References (AssemblyName, FQFileName) VALUES ('System.Drawing', 'C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Drawing.dll') 9 | INSERT INTO #References (AssemblyName, FQFileName) VALUES ('itextsharp', @FilePath + 'itextsharp.dll') 10 | 11 | DECLARE @DropWrapperSQL varchar(MAX) 12 | SET @DropWrapperSQL = ' 13 | IF OBJECT_ID(''dbo.udfRenderPDF'') IS NOT NULL BEGIN 14 | DROP FUNCTION dbo.udfRenderPDF; 15 | END 16 | ' 17 | 18 | DECLARE @CreateWrapperSQL varchar(MAX) 19 | SET @CreateWrapperSQL = ' 20 | CREATE FUNCTION [dbo].[udfRenderPDF]( 21 | @TemplatePDF varbinary(MAX), 22 | @FieldsXML xml 23 | ) 24 | RETURNS [varbinary](max) WITH EXECUTE AS CALLER 25 | AS 26 | EXTERNAL NAME [PDFCLR].[Functions].[RenderPDF] 27 | ' 28 | 29 | --C# Source Code. 30 | --Paste CLR source in below. Replace all occurrences a single quote with two single quotes. 31 | DECLARE @SourceCode nvarchar(MAX) 32 | SET @SourceCode = ' 33 | //------start of CLR Source------ 34 | using System; 35 | using System.Data; 36 | using System.Data.SqlClient; 37 | using System.Data.SqlTypes; 38 | using Microsoft.SqlServer.Server; 39 | 40 | ....Rest of C# source code goes here 41 | 42 | //------end of CLR Source------ ' 43 | 44 | 45 | EXEC dbo.spsysBuildCLRAssembly 46 | @AssemblyName = 'PDFCLR', 47 | @FileName = 'PDFCLR_SQLCLR.cs', 48 | @FilePath = @FilePath, 49 | @DropWrapperSQL = @DropWrapperSQL, 50 | @CreateWrapperSQL = @CreateWrapperSQL, 51 | @SourceCode = @SourceCode 52 | END -------------------------------------------------------------------------------- /Stored_Procedure/dbo.sp_FailedLogins.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Original link: https://sqlundercover.com/2017/06/06/undercover-toolbox-sp_failedlogins-capture-those-failed-logins-with-ease 3 | Author: David Fowler 4 | */ 5 | 6 | USE [master] 7 | GO 8 | 9 | CREATE PROCEDURE [dbo].[sp_FailedLogins] 10 | 11 | ( 12 | @FromDate DATETIME = NULL, 13 | @ToDate DATETIME = NULL 14 | ) 15 | AS 16 | 17 | BEGIN 18 | --Failed login attempts in the last 60 minutes 19 | 20 | IF @FromDate IS NULL BEGIN SET @FromDate = DATEADD(MINUTE,-60,GETDATE()) END 21 | IF @ToDate IS NULL BEGIN SET @ToDate = GETDATE() END 22 | 23 | IF OBJECT_ID('Tempdb..#Errors') IS NOT NULL 24 | DROP TABLE #Errors 25 | 26 | CREATE TABLE #Errors 27 | ( 28 | Logdate Datetime, 29 | Processinfo Varchar(30), 30 | Text Varchar (255) 31 | ) 32 | INSERT INTO #Errors 33 | EXEC xp_ReadErrorLog 0, 1, N'FAILED',N'login',@FromDate,@ToDate; 34 | 35 | SELECT 36 | REPLACE(LoginErrors.Username,'''','') AS Username, 37 | CAST(LoginErrors.Attempts AS NVARCHAR(6)) AS Attempts, 38 | LatestDate.Logdate, 39 | Latestdate.LastError 40 | from ( 41 | Select SUBSTRING(text,Patindex('%''%''%',Text),charindex('.',Text)-(Patindex('%''%''%',Text))) as Username,Count(*) AS Attempts 42 | From #Errors Errors 43 | GROUP BY SUBSTRING(text,Patindex('%''%''%',Text),charindex('.',Text)-(Patindex('%''%''%',Text))) 44 | ) LoginErrors 45 | CROSS APPLY (SELECT TOP 1 Logdate,text as LastError 46 | FROM #Errors LatestDate 47 | where LoginErrors.Username = SUBSTRING(text,Patindex('%''%''%',Text),charindex('.',Text)-(Patindex('%''%''%',Text))) 48 | ORDER by Logdate DESC) LatestDate 49 | 50 | Order by LoginErrors.Attempts DESC 51 | 52 | END 53 | GO 54 | -------------------------------------------------------------------------------- /Stored_Procedure/dbo.sp_GenerateMerge.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/Stored_Procedure/dbo.sp_GenerateMerge.sql -------------------------------------------------------------------------------- /Stored_Procedure/dbo.sp_IndexAnalysis-v11.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/Stored_Procedure/dbo.sp_IndexAnalysis-v11.sql -------------------------------------------------------------------------------- /Stored_Procedure/dbo.sp_generate_merge.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/Stored_Procedure/dbo.sp_generate_merge.sql -------------------------------------------------------------------------------- /Stored_Procedure/dbo.usp_FindDbObjects.sql: -------------------------------------------------------------------------------- 1 | CREATE PROCEDURE [dbo].[usp_FindDbObjects] 2 | @string NVARCHAR(MAX) = '' 3 | AS 4 | BEGIN 5 | 6 | SET NOCOUNT ON 7 | SET ANSI_WARNINGS OFF 8 | 9 | -- Returns list of DB objects containing the string in their definition and/or in their name. 10 | SELECT [DB_ObjName] = OBJECT_SCHEMA_NAME(sm.[object_id]) + '.' + OBJECT_NAME(sm.[object_id]), so.type_desc [DB_ObjType], 11 | (LEN(sm.[definition]) - LEN(REPLACE(sm.[definition], CHAR(10), ''))) Lines_of_Code 12 | FROM SYS.SQL_MODULES sm 13 | INNER JOIN SYS.OBJECTS so 14 | ON sm.[OBJECT_ID] = so.[OBJECT_ID] 15 | WHERE sm.[definition] LIKE N'%' + @string + '%' 16 | OR so.[name] like N'%' + @string + '%' 17 | GROUP BY sm.[object_id], so.type_desc,sm.[definition] 18 | ORDER BY [DB_ObjName], [DB_ObjType]; 19 | 20 | SET NOCOUNT OFF 21 | SET ANSI_WARNINGS ON 22 | 23 | END -------------------------------------------------------------------------------- /Stored_Procedure/dbo.usp_PrintDebug.sql: -------------------------------------------------------------------------------- 1 | IF OBJECT_ID('dbo.usp_PrintDebug', 'P') IS NULL 2 | EXECUTE('CREATE PROCEDURE dbo.usp_PrintDebug AS SELECT 1') ; 3 | GO 4 | 5 | 6 | ALTER PROCEDURE dbo.usp_PrintDebug 7 | ( 8 | @variableName NVARCHAR(MAX) = '', 9 | @variableValue NVARCHAR(MAX) = '', 10 | @printMessage NVARCHAR(MAX) = '' 11 | ) 12 | /* 13 | EXECUTE dbo.usp_PrintDebug @variableName = 'maxDate', @variableValue = '' 14 | EXECUTE dbo.usp_PrintDebug @printMessage = 'start_debug' 15 | EXECUTE dbo.usp_PrintDebug @printMessage = 'end_debug' 16 | EXECUTE dbo.usp_PrintDebug @printMessage = 'Test debug' 17 | */ 18 | AS 19 | BEGIN 20 | DECLARE @Crlf NVARCHAR(10) = CHAR(13) ; 21 | BEGIN TRY 22 | IF @printMessage = '' 23 | IF @variableValue IS NOT NULL AND CAST(@variableValue AS NVARCHAR) != '' 24 | PRINT '@' + @variableName + ' = {' + CAST(@variableValue AS NVARCHAR) + '}' 25 | ELSE 26 | IF CAST(@variableValue AS NVARCHAR) = '' 27 | PRINT @variableName + ' = {Empty String}' 28 | ELSE 29 | IF @variableValue IS NULL 30 | PRINT @variableName + ' = {NULL}'; 31 | 32 | IF @printMessage LIKE 'start_debug %' 33 | PRINT '/******* Start Debug' + REPLACE(@printMessage, 'start_debug' , ' ') + @Crlf; 34 | 35 | IF @printMessage LIKE 'end_debug %' 36 | PRINT @Crlf + '--End Deubg ' + REPLACE(@printMessage, 'end_debug' , '') + ' *********/'; 37 | 38 | IF @printMessage NOT LIKE '%_debug%' 39 | PRINT @printMessage; 40 | END TRY 41 | 42 | BEGIN CATCH 43 | EXECUTE usp_LogError; 44 | END CATCH 45 | END; 46 | go 47 | -------------------------------------------------------------------------------- /Stored_Procedure/dbo.usp_PrintError.sql: -------------------------------------------------------------------------------- 1 | IF OBJECT_ID('[dbo].[usp_PrintError]', 'P') IS NULL 2 | EXECUTE('CREATE PROCEDURE [dbo].[usp_PrintError] AS SELECT 1'); 3 | go 4 | 5 | 6 | ALTER PROCEDURE [dbo].[usp_PrintError] 7 | AS 8 | BEGIN 9 | SET NOCOUNT ON; 10 | 11 | -- Print error information. 12 | PRINT 'Error: ' + CONVERT(varchar(50), ERROR_NUMBER()) + 13 | ', Severity: ' + CONVERT(varchar(5), ERROR_SEVERITY()) + 14 | ', State: ' + CONVERT(varchar(5), ERROR_STATE()) + 15 | ', Procedure: ' + ISNULL(ERROR_PROCEDURE(), '-') + 16 | ', Line: ' + CONVERT(varchar(5), ERROR_LINE()) + 17 | ', User name: ' + CONVERT(sysname, CURRENT_USER); 18 | PRINT ERROR_MESSAGE(); 19 | END; 20 | go 21 | -------------------------------------------------------------------------------- /Stored_Procedure/dbo.usp_RandomWait.sql: -------------------------------------------------------------------------------- 1 | ---------------------------------------------------------------------------------------------------------------- 2 | --Procedure to wait randomized number of minutes or seconds, used to delay jobs 3 | ---------------------------------------------------------------------------------------------------------------- 4 | IF OBJECT_ID('usp_RandomWait') IS NOT NULL DROP PROC usp_RandomWait 5 | GO 6 | 7 | CREATE PROC usp_RandomWait 8 | @sec_or_min char(1) = 'm' 9 | ,@span tinyint = 30 10 | AS 11 | IF @sec_or_min NOT IN ('s', 'm') 12 | BEGIN 13 | RAISERROR('The parameter @sec_or_min must be ''m'' (minutes) or ''s'' (seconds).', 16, 1) 14 | RETURN 15 | END 16 | DECLARE @towait char(2) 17 | ,@parsedWait char(8) 18 | ,@msg varchar(100) 19 | SET @towait = RIGHT('0' + CAST(CAST(RAND()*@span AS int)%@span+1 AS varchar(2)), 2) 20 | SET @parsedWait = 21 | CASE WHEN @sec_or_min = 's' THEN '00:00:' + @towait 22 | ELSE '00:' + @towait + ':00' 23 | END 24 | SET @msg = 'Waiting ' + @parsedWait 25 | RAISERROR (@msg, 10, 1) WITH NOWAIT 26 | WAITFOR DELAY @parsedWait 27 | 28 | /* Test 29 | EXEC usp_RandomWait 30 | EXEC usp_RandomWait @sec_or_min = 'm', @span = 30 31 | EXEC usp_RandomWait @sec_or_min = 's', @span = 10 32 | */ 33 | GO 34 | -------------------------------------------------------------------------------- /Stored_Procedure/dbo.usp_checkAllDatabases.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Original link: http://stevestedman.com/2015/09/dbcc-checkdb-all-databases/ 3 | Author: Steve Stedman 4 | */ 5 | 6 | IF OBJECT_ID('dbo.usp_checkAllDatabases') IS NULL 7 | EXEC sp_executesql N'CREATE PROCEDURE dbo.usp_checkAllDatabases AS SELECT 1;' 8 | GO 9 | 10 | ALTER PROCEDURE usp_checkAllDatabases 11 | AS 12 | /* 13 | EXEC usp_checkAllDatabases; 14 | */ 15 | BEGIN 16 | DECLARE @databaseList as CURSOR; 17 | DECLARE @databaseName as NVARCHAR(500); 18 | DECLARE @tsql AS NVARCHAR(500); 19 | 20 | SET @databaseList = CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY 21 | FOR 22 | SELECT QUOTENAME([name]) 23 | FROM sys.databases 24 | WHERE [state] = 0 25 | AND [is_read_only] = 0; 26 | OPEN @databaseList; 27 | FETCH NEXT FROM @databaseList into @databaseName; 28 | WHILE @@FETCH_STATUS = 0 29 | BEGIN 30 | SET @tsql = N'DBCC CheckDB(' + @databaseName + ') WITH NO_INFOMSGS;'; 31 | EXECUTE (@tsql); 32 | FETCH NEXT FROM @databaseList into @databaseName; 33 | END 34 | CLOSE @databaseList; 35 | DEALLOCATE @databaseList; 36 | END 37 | GO 38 | -------------------------------------------------------------------------------- /User_Defined_Function/dbo.ConvertHexLSN.sql: -------------------------------------------------------------------------------- 1 | IF OBJECT_ID('dbo.udf_ConvertHexLSN') IS NULL 2 | EXECUTE ('CREATE FUNCTION udf_ConvertHexLSN() RETURNS TABLE AS RETURN SELECT 1 AS A;'); 3 | GO 4 | 5 | 6 | ALTER FUNCTION dbo.udf_ConvertHexLSN( 7 | @lsnc varchar(25) 8 | ) 9 | /* 10 | Author: Max Vernon 11 | Original link: https://www.sqlserverscience.com/internals/convert-lsn-hex-decimal/ 12 | 13 | SELECT * FROM dbo.udf_ConvertHexLSN('00000268:0000356c:0001'); 14 | */ 15 | RETURNS TABLE 16 | WITH SCHEMABINDING 17 | AS 18 | RETURN 19 | ( 20 | SELECT TOP(1) 21 | LSNd = CONVERT(varchar(8), CONVERT(int, CONVERT(varbinary(8), '0x' + CONVERT(varchar(10), LEFT(@lsnc, 8), 0), 1), 1)) 22 | + ':' + CONVERT(varchar(8), CONVERT(int, CONVERT(varbinary(8), '0x' + CONVERT(varchar(10), SUBSTRING(@lsnc, 10, 8), 0), 1)), 1) 23 | + ':' + CONVERT(varchar(8), CONVERT(int, CONVERT(varbinary(8), '0x' + CONVERT(varchar(10), RIGHT(@lsnc, 4), 0), 1), 1)) 24 | ); 25 | GO 26 | -------------------------------------------------------------------------------- /User_Defined_Function/fnWordDifference.sql: -------------------------------------------------------------------------------- 1 | CREATE FUNCTION [dbo].[fnWordDifference] ( 2 | @First VarChar(256) 3 | ,@Second VarChar(256) 4 | ,@Difference TinyInt = NULL 5 | ) RETURNS TABLE AS RETURN -- SELECT * FROM dbo.fnWordDifference('012345679012','012456789012',3) 6 | WITH Shift(Position,[Left],[Right],[Difference]) AS ( 7 | SELECT 0 8 | ,@First 9 | ,@Second 10 | ,0 11 | WHERE @Difference >= 0 OR @Difference IS NULL 12 | UNION ALL 13 | SELECT Position + 1 14 | ,[Left] 15 | ,[Right] 16 | ,[Difference] 17 | FROM Shift 18 | WHERE Position <= Len([Left] ) 19 | AND Position <= Len([Right]) 20 | AND SubString([Left] ,Position + 1,1) 21 | = SubString([Right],Position + 1,1) 22 | UNION ALL 23 | SELECT Position 24 | ,Convert(VarChar(256),Stuff([Left],Position + 1,1,'')) 25 | ,[Right] 26 | ,[Difference] + 1 27 | FROM Shift 28 | WHERE Position <= Len([Left] ) 29 | AND Position <= Len([Right]) 30 | AND SubString([Left] + ' ',Position + 1,1) 31 | != SubString([Right] + ' ',Position + 1,1) 32 | AND([Difference] < @Difference OR @Difference IS NULL) 33 | UNION ALL 34 | SELECT Position 35 | ,[Left] 36 | ,Convert(VarChar(256),Stuff([Right],Position + 1,1,'')) 37 | ,[Difference] + 1 38 | FROM Shift 39 | WHERE Position <= Len([Left] ) 40 | AND Position <= Len([Right]) 41 | AND SubString([Left] + ' ',Position + 1,1) 42 | != SubString([Right]+ ' ',Position + 1,1) 43 | AND([Difference] < @Difference OR @Difference IS NULL) 44 | ) SELECT Top(1) 45 | @First AS [First] 46 | ,@Second AS [Second] 47 | ,[Left] AS [Root] 48 | ,[Difference] 49 | FROM Shift 50 | WHERE [Left] = [Right] AND Position = Len([Left]) 51 | ORDER BY [Difference] 52 | -------------------------------------------------------------------------------- /User_Defined_Function/udf_CheckDynamicSQL.sql: -------------------------------------------------------------------------------- 1 | IF OBJECT_ID('dbo.udf_CheckDynamicSQL', 'FN') IS NULL 2 | EXECUTE ('CREATE FUNCTION dbo.udf_CheckDynamicSQL() RETURNS INT AS BEGIN RETURN 1 END;'); 3 | GO 4 | 5 | ALTER FUNCTION dbo.udf_CheckDynamicSQL( 6 | @dynamicSQL NVARCHAR (MAX) 7 | ) 8 | RETURNS NVARCHAR (2000) 9 | AS 10 | /* 11 | .SYNOPSIS 12 | Check Dynamic SQL Statement Syntax 13 | 14 | .DESCRIPTION 15 | Check Dynamic SQL Statement Syntax first output result using sys.dm_exec_describe_first_result_set 16 | https://docs.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-exec-describe-first-result-set-transact-sql 17 | 18 | .PARAMETER @dynamicSQL 19 | Dynamic SQL statement for checking 20 | 21 | .EXAMPLE 22 | SELECT dbo.udf_CheckDynamicSQL('SELECT * , FROM sys.databases;'); 23 | -- RETURN: Incorrect syntax near the keyword 'FROM'. 24 | 25 | .EXAMPLE 26 | SELECT dbo.udf_CheckDynamicSQL('SELECT TOP(1) * FROM sys.databases;'); 27 | --RETURN: OK 28 | 29 | .NOTE 30 | Author: Eli Leiba 31 | Source link: https://www.mssqltips.com/sqlservertip/4981/sql-server-function-to-check-dynamic-sql-syntax/ 32 | */ 33 | BEGIN 34 | DECLARE @Result NVARCHAR (2000); 35 | 36 | IF EXISTS ( 37 | SELECT 1 38 | FROM sys.dm_exec_describe_first_result_set (@dynamicSQL, NULL, 0) 39 | WHERE [error_message] IS NOT NULL 40 | AND [error_number] IS NOT NULL 41 | AND [error_severity] IS NOT NULL 42 | AND [error_state] IS NOT NULL 43 | AND [error_type] IS NOT NULL 44 | AND [error_type_desc] IS NOT NULL 45 | ) 46 | BEGIN 47 | SELECT @Result = [error_message] 48 | FROM sys.dm_exec_describe_first_result_set(@dynamicSQL, NULL, 0) 49 | WHERE column_ordinal = 0; 50 | END 51 | ELSE 52 | BEGIN 53 | SET @Result = 'OK' 54 | END 55 | 56 | RETURN (@Result); 57 | END 58 | GO 59 | -------------------------------------------------------------------------------- /User_Defined_Function/udf_DateFormattedByMask.sql: -------------------------------------------------------------------------------- 1 | CREATE FUNCTION [dbo].[udf_DateFormattedByMask] 2 | ( 3 | @InputDate DATETIME, 4 | @Mask NVARCHAR(40) 5 | ) 6 | /* 7 | YYYY - Year, 4 digit 8 | YY - Year, 2 digit 9 | MMMM - Month name 10 | MMM - Month name, first 3 characters 11 | MM - Month, 2 digit 12 | DDDD - Day of week 13 | DDD - Day of week, first 3 characters 14 | DD - Day of month, 2 digit 15 | hh - hour (24 hour clock, 2 digit) 16 | mi - minutes, 2 digit 17 | ss - seconds, 2 digit 18 | */ 19 | RETURNS VARCHAR(40) 20 | AS 21 | BEGIN 22 | 23 | 24 | SELECT @Mask = REPLACE(@Mask,'YYYY',DATENAME(YEAR,@InputDate)) 25 | SELECT @Mask = REPLACE(@Mask,'YY',RIGHT(DATENAME(YEAR,@InputDate),2)) 26 | SELECT @Mask = REPLACE(@Mask,'MMMM', DATENAME(MONTH,@InputDate)) 27 | SELECT @Mask = REPLACE(@Mask,'MMM', LEFT(DATENAME(MONTH,@InputDate),3)) 28 | SELECT @Mask = REPLACE(@Mask,'MM', RIGHT('0'+CAST(MONTH(@InputDate) AS NVARCHAR(2)),2)) 29 | SELECT @Mask = REPLACE(@Mask,'DDDD', DATENAME(dw,@InputDate)) 30 | SELECT @Mask = REPLACE(@Mask,'DDD', LEFT(DATENAME(dw,@InputDate),3)) 31 | SELECT @Mask = REPLACE(@Mask,'DD', RIGHT('0'+DATENAME(DAY,@InputDate),2)) 32 | SELECT @Mask = REPLACE(@Mask,'hh', RIGHT('0'+DATENAME(hh,@InputDate),2)) 33 | SELECT @Mask = REPLACE(@Mask,'mi', RIGHT('0'+DATENAME(mi,@InputDate),2)) 34 | SELECT @Mask = REPLACE(@Mask,'ss', RIGHT('0'+DATENAME(ss,@InputDate),2)) 35 | 36 | RETURN @Mask 37 | 38 | END 39 | 40 | GO 41 | -------------------------------------------------------------------------------- /User_Defined_Function/udf_FindPosition.sql: -------------------------------------------------------------------------------- 1 | CREATE FUNCTION dbo.udf_FindPosition 2 | ( 3 | @strInput varchar ( 8000 4 | ) 5 | , 6 | @delimiter varchar ( 50 7 | ) 8 | ) 9 | RETURNS TABLE 10 | AS 11 | RETURN 12 | 13 | WITH findchar ( posnum, 14 | pos 15 | ) 16 | AS ( 17 | SELECT 1 AS posnum, 18 | CHARINDEX ( @delimiter, @strInput 19 | ) AS pos 20 | UNION ALL 21 | SELECT f.posnum + 1 AS posnum, 22 | CHARINDEX ( @delimiter, @strInput, f.pos + 1 23 | ) AS pos 24 | FROM findchar AS f 25 | WHERE f.posnum + 1 <= LEN ( @strInput 26 | ) 27 | AND 28 | pos <> 0 29 | ) 30 | SELECT posnum 31 | , 32 | pos 33 | FROM findchar 34 | WHERE 35 | pos > 0; 36 | 37 | GO 38 | -------------------------------------------------------------------------------- /User_Defined_Function/udf_Haversine.sql: -------------------------------------------------------------------------------- 1 | CREATE FUNCTION HAVERSINE (lat1 DOUBLE, lon1 DOUBLE, lat2 DOUBLE, lon2 DOUBLE) 2 | RETURNS DOUBLE 3 | DETERMINISTIC 4 | BEGIN 5 | DECLARE dist DOUBLE; 6 | SET dist = round(acos(cos(radians(lat1))*cos(radians(lon1))*cos(radians(lat2))*cos(radians(lon2)) + cos(radians(lat1))*sin(radians(lon1))*cos(radians(lat2))*sin(radians(lon2)) + sin(radians(lat1))*sin(radians(lat2))) * 6372.8, 1); 7 | RETURN dist; 8 | END 9 | -------------------------------------------------------------------------------- /User_Defined_Function/udf_INSTR.sql: -------------------------------------------------------------------------------- 1 | IF OBJECT_ID('dbo.udf_INSTR', 'IF') IS NULL 2 | EXECUTE ('CREATE FUNCTION dbo.udf_INSTR() RETURNS TABLE AS RETURN SELECT 1 AS A;'); 3 | GO 4 | 5 | 6 | ALTER FUNCTION dbo.udf_INSTR( 7 | @str NVARCHAR(4000), 8 | @substr NVARCHAR(4000), 9 | @start INT, 10 | @Occurance INT 11 | ) 12 | RETURNS TABLE 13 | AS 14 | /* 15 | Note 16 | Author: Hannan Kravitz 17 | Original link: http://www.sqlservercentral.com/scripts/SUBSTRING/148570/ 18 | Modified Date: 2016-11-17 19 | Example: 20 | SELECT Loc FROM dbo.udf_INSTR ('Hello World', 'l', 1, 1) -- return 3 21 | SELECT Loc FROM dbo.udf_INSTR ('Hello World', 'l', 1, 3) -- return 10 22 | SELECT Loc FROM dbo.udf_INSTR ('Hello World', 'l', 1, 4) -- return NULL 23 | SELECT Loc FROM dbo.udf_INSTR ('Ёжик - это моё имя','ё', 1, 1) -- return 14 24 | */ 25 | RETURN 26 | WITH Tally(N) AS 27 | ( 28 | SELECT TOP (LEN(@str)) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) 29 | FROM (VALUES (0),(0),(0),(0),(0),(0),(0),(0)) a(N) 30 | CROSS JOIN (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) b(N) 31 | CROSS JOIN (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) c(N) 32 | CROSS JOIN (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) d(N) 33 | ) 34 | , Find_N_STR AS 35 | ( 36 | SELECT 37 | CASE WHEN DENSE_RANK() OVER(PARTITION BY @substr ORDER BY (CHARINDEX(@substr, @str, N))) = @Occurance 38 | THEN MAX(N - @start + 1) OVER (PARTITION BY CHARINDEX(@substr, @str, N)) 39 | ELSE 0 40 | END [Loc] 41 | FROM Tally 42 | WHERE CHARINDEX(@substr, @str, N) > 0 43 | ) 44 | SELECT Loc= MAX(Loc) 45 | FROM Find_N_STR 46 | WHERE Loc > 0; 47 | GO 48 | -------------------------------------------------------------------------------- /User_Defined_Function/udf_IsValidCard.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/User_Defined_Function/udf_IsValidCard.sql -------------------------------------------------------------------------------- /User_Defined_Function/udf_PatternSplitLoop.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/User_Defined_Function/udf_PatternSplitLoop.sql -------------------------------------------------------------------------------- /User_Defined_Function/udf_RemoveNonAlphaCharacters.sql: -------------------------------------------------------------------------------- 1 | IF OBJECT_ID('dbo.udf_RemoveNonAlphaCharacters') IS NULL 2 | EXECUTE ('CREATE FUNCTION dbo.udf_RemoveNonAlphaCharacters() RETURNS NVARCHAR(MAX) AS RETURN SELECT 1 AS A;'); 3 | GO 4 | 5 | 6 | ALTER FUNCTION dbo.udf_RemoveNonAlphaCharacters( 7 | @inputString NVARCHAR(MAX) 8 | , @keepValues NVARCHAR(1000) = N'%[^a-z0-9]%' 9 | ) 10 | RETURNS NVARCHAR(MAX) 11 | /* 12 | SELECT dbo.udf_RemoveNonAlphaCharacters(N'Тестовая строка - Test string 123_456', N'%[^a-z0-9]%'); 13 | SELECT dbo.udf_RemoveNonAlphaCharacters(N'Тестовая строка - Test string 123_456', N'%[^3-9]%'); 14 | */ 15 | AS 16 | BEGIN 17 | WHILE PATINDEX(@keepValues, @inputString) > 0 18 | SET @inputString = STUFF(@inputString, PATINDEX(@keepValues, @inputString), 1, ''); 19 | 20 | RETURN @inputString; 21 | END; 22 | GO 23 | -------------------------------------------------------------------------------- /User_Defined_Function/udf_SplitStringByDelimiter.sql: -------------------------------------------------------------------------------- 1 | IF OBJECT_ID('dbo.udf_SplitStringByDelimiter', 'IF') IS NULL 2 | EXECUTE('CREATE FUNCTION dbo.udf_SplitStringByDelimiter() RETURNS TABLE WITH SCHEMABINDING AS RETURN SELECT 1 AS A;'); 3 | GO 4 | 5 | 6 | ALTER FUNCTION dbo.udf_SplitStringByDelimiter( 7 | @List NVARCHAR(MAX), 8 | @Delimiter NVARCHAR(MAX) 9 | ) 10 | RETURNS TABLE 11 | WITH SCHEMABINDING AS 12 | RETURN 13 | WITH E1(N) AS ( SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 14 | UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 15 | UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1), 16 | E2(N) AS (SELECT 1 FROM E1 a, E1 b), 17 | E4(N) AS (SELECT 1 FROM E2 a, E2 b), 18 | E42(N) AS (SELECT 1 FROM E4 a, E2 b), 19 | cteTally(N) AS (SELECT 0 UNION ALL SELECT TOP (DATALENGTH(ISNULL(@List,1))) 20 | ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E42), 21 | cteStart(N1) AS (SELECT t.N+1 FROM cteTally t 22 | WHERE (SUBSTRING(@List,t.N,1) = @Delimiter OR t.N = 0)) 23 | SELECT Item = SUBSTRING(@List, s.N1, ISNULL(NULLIF(CHARINDEX(@Delimiter,@List,s.N1),0)-s.N1,8000)) 24 | FROM cteStart s; 25 | GO 26 | -------------------------------------------------------------------------------- /User_Defined_Function/udf_Tally.sql: -------------------------------------------------------------------------------- 1 | CREATE FUNCTION [dbo].[udf_Tally] 2 | ( 3 | @pMin BIGINT 4 | ,@pMax BIGINT 5 | ) 6 | RETURNS TABLE 7 | WITH SCHEMABINDING 8 | AS 9 | RETURN 10 | 11 | /* Uses the Bates algorithm for generating the rows from */ 12 | /* http://www.sqlservercentral.com/scripts/Tally+Table/99617/ */ 13 | 14 | /* 15 | Usage: 16 | SELECT N FROM [dbo].[itvfTally](1001,1100) 17 | SELECT N FROM [dbo].[itvfTally](-10,100) 18 | SELECT N FROM [dbo].[itvfTally](0,1000) 19 | SELECT N FROM [dbo].[itvfTally](1,1000) 20 | */ 21 | 22 | WITH T1(F) AS 23 | ( 24 | SELECT 1 UNION ALL 25 | SELECT 1 UNION ALL 26 | SELECT 1 UNION ALL 27 | SELECT 1 UNION ALL 28 | SELECT 1 UNION ALL 29 | SELECT 1 UNION ALL 30 | SELECT 1 UNION ALL 31 | SELECT 1 UNION ALL 32 | SELECT 1 UNION ALL 33 | SELECT 1 34 | ), 35 | T2(F) AS 36 | (SELECT 1 FROM T1 A, T1 B), 37 | T3(F) AS 38 | (SELECT 1 FROM T2 A, T2 B), 39 | T4(F) AS 40 | (SELECT 1 FROM T3 A, T3 B), 41 | cteTally(N) AS 42 | ( 43 | SELECT TOP ((@pMax-(((ABS(@pMin)+@pMin)/2)))+1) 44 | ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) 45 | + ((((ABS(@pMin)+@pMin)/2))-1) 46 | FROM T4 47 | ) 48 | SELECT 49 | N 50 | FROM 51 | cteTally T 52 | ; -------------------------------------------------------------------------------- /img/microsoft-sql-server-logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exajobs/SQL-server-collection/79c63e7fe83e8f9b80fd0c15e641e56b7c996b27/img/microsoft-sql-server-logo.png --------------------------------------------------------------------------------