├── .gitattributes ├── .github ├── ISSUE_TEMPLATE.md └── PULL_REQUEST_TEMPLATE.md ├── .gitignore ├── 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 ├── README.md └── regedit_sqlserver.png ├── Extended_Events ├── APC_Reverted_plan_corrections.sql ├── APC_plans_that_are_not_corrected.sql ├── BackupRestoreTrace.sql ├── ConvertingSQLTracetoExtendedEvents.sql ├── DarkQueries.sql ├── Deadlocks.sql ├── InvestigateWaits.sql ├── LoginFailure.sql ├── MonitorPageSplits.sql ├── README.md ├── Recompile_Histogram.sql ├── TrackPageSplits.sql └── system_health.sql ├── LICENSE.md ├── PowerShell ├── Add-UserToRole.ps1 ├── Clone-SQLLogin.ps1 ├── Compare-Server-Settings.ps1 ├── Create-Deploy-SQL-Script.ps1 ├── CsvSqlimport.ps1 ├── Export-AllPlans.ps1 ├── Fast_table_to_csv.ps1 ├── Get-CmsHosts.ps1 ├── Get-MachineInformationExcel.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 ├── README.md ├── ResetSqlSaPassword.psm1 ├── SQL_Server_Test_backups.ps1 ├── SQL_Server_linked_server_connection_check.ps1 ├── SQL_Server_table_to_csv.ps1 ├── Set_Extended_Events_Sessions_to_AutoStart.ps1 ├── Shred-XElogs.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_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 │ ├── 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 │ ├── 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 │ ├── 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_2014(12.0.5556).vssettings │ └── README.md ├── Scripts ├── AutoGuessingForeignKeyConstraints.sql ├── Azure SQL Database Diagnostic Information Queries.sql ├── Backup_Restore_What’s_My_Status.sql ├── Blocked_Session.sql ├── BufferPoolExtension.sql ├── CPU_Utilization.sql ├── CPU_Utilization_Graphical_form.sql ├── Checking_Your_Backup_Paths_Exist_and_Automatically_Create_it.sql ├── Compare_2_tables_by_column_names.sql ├── Count character matches.sql ├── Current_Running_Queries.sql ├── Current_Running_Tasks_and_Server_Info.sql ├── Database_Mail_Configuration.sql ├── Date Calendar Cross-Reference Table.sql ├── Date_Format_Cheat_Sheet.sql ├── Decrypt T-SQL module.sql ├── DetermineSpaceWithinSQLDatabaseFiles.sql ├── Drop_all_objects_in_schema.sql ├── DynamicallyGenerateDMAStatement.sql ├── Enable Microsoft.ACE.OLEDB.12.0.sql ├── Estimate_When_Long_Running_SQL_Processes_Will_Finish.sql ├── FindDBConnectionLeaks.sql ├── FindLongRunningJobSteps.sql ├── FindTablesWithSimilarTableStructure.sql ├── Find_Non_Sargable_Queries.sql ├── Find_Synonyms_for_nested_objects_in_the_different_databases.sql ├── Find_Synonyms_for_nested_objects_in_the_same_database.sql ├── FindingImplicitColumnConversionsInPlanCache.sql ├── FindingSpecificColumns.sql ├── Finding_Blocking_Queries.sql ├── Foreign_Key_batch_rename.sql ├── GenerateTSQLTimeSlices.sql ├── Generate_Restore_Script_From_Backup_Folder.sql ├── Generate_table_definition_to_match_query.sql ├── GetResourceNameFromBlockedProcessReport.sql ├── Get_Database_Size_With_Graph.sql ├── Get_Statistics_Details.sql ├── Get_Table_Hierarchy.sql ├── GoogleJobTimeline.sql ├── How_old_your_backups.sql ├── How_to_Find_Queries_Using_an_Index.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 ├── Indexes_Script_Out.sql ├── LatchStats.sql ├── Listing_SQL_Agent_Jobs_Running_at_a_Specific_Time.sql ├── MAXDOP_recommendation.sql ├── MaxServerMemoryCalculator.sql ├── MisleadingSQLServerPerformanceCounters.sql ├── Monitor_Deadlocks_with_Extended_Events.sql ├── Move_tempdb.sql ├── New_Default_Database_Assignment_For_Any_Login_Missing_Their_Default_Database.sql ├── ObjectSizes.sql ├── PowerSavingCheck.sql ├── Queries_vulnerable_to_SQL_injection.sql ├── QueryActiveDirectory.sql ├── README.md ├── RenameDefaultConstraints.sql ├── Restore_script_for_Ola_Hallengren_backup.sql ├── Ring_Bufer_Analyze.sql ├── Run_scripts.bat ├── 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 2017 Diagnostic Information Queries.sql ├── SQL_Server_Fixed_Role_Permissions.sql ├── Search_Script.sql ├── Server_Parameters.sql ├── Show all permissions in a database.sql ├── ShredDeadlockGraph.sql ├── ShredDeadlockGraph_Sample1.xml ├── ShredDeadlockGraph_Sample2.xml ├── Space used by object.sql ├── SpaceusedByTable.sql ├── SplitFileGroup.sql ├── Stop_long-running_SQL_Server_Agent_Jobs.sql ├── Suspect_Database_Pages.sql ├── Table Count alternative.sql ├── Table_Parameters.sql ├── Table_and_Index_storage_size.sql ├── Table_upload_order.sql ├── Tempdb_Contention.sql ├── Temporal_Table_Maker.sql ├── Truncate log file.sql ├── TuneYourIndexingStrategyWithDMVs.sql ├── UnPivot_Output_Restore_Headeronly.sql ├── Visualizing_Agent_Jobs_in_SSMS.sql ├── Visualizing_VLF.sql ├── Wait_Statistics.sql ├── What_Agent_Job_is_Running.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_database.sql ├── Windows logins not in AD.sql └── tempdb_Information.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 ├── SQLQueryStress │ ├── .gitignore │ ├── CONTRIBUTING.md │ ├── README.md │ └── src │ │ ├── SQLQueryStress.sln │ │ └── SQLQueryStress │ │ ├── AboutBox.Designer.cs │ │ ├── AboutBox.cs │ │ ├── AboutBox.resx │ │ ├── App.config │ │ ├── BlockedBoundedBuffer.cs │ │ ├── DataViewer.Designer.cs │ │ ├── DataViewer.cs │ │ ├── DataViewer.resx │ │ ├── DatabaseSelect.Designer.cs │ │ ├── DatabaseSelect.cs │ │ ├── DatabaseSelect.resx │ │ ├── Form1.Designer.cs │ │ ├── Form1.cs │ │ ├── Form1.resx │ │ ├── LoadEngine.cs │ │ ├── Options.Designer.cs │ │ ├── Options.cs │ │ ├── Options.resx │ │ ├── ParamWindow.Designer.cs │ │ ├── ParamWindow.cs │ │ ├── ParamWindow.resx │ │ ├── Program.cs │ │ ├── Properties │ │ ├── AssemblyInfo.cs │ │ ├── Resources.Designer.cs │ │ ├── Resources.resx │ │ ├── Settings.Designer.cs │ │ ├── Settings.settings │ │ └── app.manifest │ │ ├── Resources │ │ └── QueryStressIcon.ico │ │ ├── SQLQueryStress.csproj │ │ ├── SQLQueryStress_Documentation.doc │ │ └── sqlQueryStress.snk ├── 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 ├── dbo.sp_Snapshot.sql ├── sp_AllocationMetadata.sql ├── sp_BenchmarkTSQL.sql ├── sp_BlitzInMemoryOLTP.sql ├── sp_Blocked_Process_Report_Viewer.sql ├── sp_ChangeDatabaseOwnerShip.sql ├── sp_DBA_job_notification.sql ├── sp_DBPermissions.sql ├── sp_Defrag_Indexes.sql ├── sp_DropIndexes.sql ├── sp_Example_RegisterAssembly_PDFCLR.sql ├── sp_FailedJobs.sql ├── sp_FailedLogins.sql ├── sp_IndexAnalysis-v11.sql ├── sp_RestoreGene.sql ├── sp_RestoreScript.sql ├── sp_SQLskills_ExposeColsInIndexLevels.sql ├── sp_SQLskills_helpindex.sql ├── sp_SrvPermissions.sql ├── sp_WhatsupQueryStore.sql ├── sp_capture_login_auth.sql ├── sp_ctrl3.sql ├── sp_foreign_key$batch_drop_and_recreate.sql ├── sp_generate_merge.sql ├── sp_helpExpandView.sql ├── sp_help_permissions.sql ├── sp_ns_shrink_db_log.sql ├── sp_sizing.sql ├── sp_sqltrace.sql ├── sqlg_ParseDiskskpXml.sql ├── udp_IntegerListfromRanges.sql ├── usp_Breadth_First.sql ├── usp_BulkUpload.sql ├── usp_CopyLogins.sql ├── usp_CreatePlantUMLCode.sql ├── usp_DBA_Rename_Database.sql ├── usp_Dijkstra.sql ├── usp_EnableAndAddFileStreamForDatabase.sql ├── usp_FindDbObjects.sql ├── usp_Generate_Merge.sql ├── usp_GetPackageDetails.sql ├── usp_GetUntrustedForeignKeys.sql ├── usp_Kruskal.sql ├── usp_LoadTableBlobs.sql ├── usp_LogError.sql ├── usp_MonitorIdentityColumn.sql ├── usp_Object_Search.sql ├── usp_Prim.sql ├── usp_PrintDebug.sql ├── usp_PrintError.sql ├── usp_PrintString.sql ├── usp_RandomWait.sql ├── usp_RunCheckAllUntrustedForeignKeys.sql ├── usp_SQL_Server_System_Report.sql ├── usp_SQLskillsAnalyzeLog.sql ├── usp_SSIS_ScriptEnvironment.sql ├── usp_SearchOnAllDB.sql ├── usp_SetFileGrowth.sql ├── usp_String_Search.sql ├── usp_TableUnpivot.sql ├── usp_TopologicalSort.sql ├── usp_UnusedInputParameters.sql ├── usp_bcpTableUnload.sql ├── usp_bcpTableUnloadBatchMode.sql ├── usp_bcpUnloadSelect.sql ├── usp_checkAllDatabases.sql ├── usp_generateIdentifier.sql └── usp_who5.sql ├── User_Defined_Function ├── FN_SPLIT.sql ├── README.md ├── RemoveNonAlphaCharacters.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_PatExclude8K.sql ├── udf_PatReplace8K.sql ├── udf_PatternSplitLoop.sql ├── udf_QueriesWithParameterizationProblems.sql ├── udf_RTF2Text.sql ├── udf_RenderXMLToString.sql ├── udf_SecondConvertRangesInIntegerList.sql ├── udf_SplitStringByDelimiter.sql ├── udf_StringComparisonsLevenshteinFull-matrix.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 /.gitattributes: -------------------------------------------------------------------------------- 1 | # Custom for Visual Studio 2 | *.ascx text 3 | *.cmd text 4 | *.ps1 text 5 | *.psm1 text 6 | *.coffee text 7 | *.config text 8 | *.cs text diff=csharp 9 | *.csproj text merge=union 10 | *.css text 11 | *.cshtml text 12 | *.htm text 13 | *.html text 14 | *.js text 15 | *.msbuild text 16 | *.resx text merge=union 17 | *.ruleset text 18 | *.Stylecop text 19 | *.targets text 20 | *.tt text 21 | *.txt text 22 | *.vb text 23 | *.vbhtml text 24 | *.vbproj text merge=union 25 | *.xml text 26 | *.xunit text 27 | *.sln text eol=crlf merge=union 28 | *.settings text 29 | 30 | # STANDARD TO MSYSGIT 31 | *.DOC DIFF=ASTEXTPLAIN 32 | *.DOC DIFF=ASTEXTPLAIN 33 | *.DOCX DIFF=ASTEXTPLAIN 34 | *.DOCX DIFF=ASTEXTPLAIN 35 | *.XLS binary 36 | *.XLS binary 37 | *.XLSX binary 38 | *.XLSX binary 39 | *.PPT binary 40 | *.PPTX binary 41 | *.DOT DIFF=ASTEXTPLAIN 42 | *.DOT DIFF=ASTEXTPLAIN 43 | *.PDF DIFF=ASTEXTPLAIN 44 | *.PDF DIFF=ASTEXTPLAIN 45 | *.RTF DIFF=ASTEXTPLAIN 46 | *.RTF DIFF=ASTEXTPLAIN 47 | 48 | 49 | *.JPG BINARY 50 | *.PNG BINARY 51 | *.GIF BINARY 52 | *.ICO BINARY 53 | *.BMP BINARY 54 | *.MDF BINARY 55 | *.LDF BINARY 56 | *.MAFF BINARY 57 | 58 | # EOL = lf 59 | *.HTM eol=lf merge=union 60 | *.HTML eol=lf merge=union 61 | *.MD eol=lf merge=union 62 | 63 | # T-SQL files 64 | *.sql eol=crlf merge=union 65 | /*.sql diff 66 | *.sql diff 67 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | **Do you want to request a *feature* or report a *bug*?** 2 | 3 | **What is the current behavior?** 4 | 5 | **If the current behavior is a bug, please provide the steps to reproduce and if possible a minimal demo of the problem via http://sqlfiddle.com/** 6 | 7 | **What is the expected behavior?** 8 | 9 | **Which versions of SQL Server and which OS are affected by this issue? Did this work in previous versions of our procedures?** 10 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | Fixes # . 2 | 3 | Changes proposed in this pull request: 4 | - 5 | - 6 | - 7 | 8 | How to test this code: 9 | - 10 | - 11 | - 12 | 13 | Has been tested on (remove any that don't apply): 14 | - Case-sensitive SQL Server instance 15 | - SQL Server 2008 16 | - SQL Server 2008 R2 17 | - SQL Server 2012 18 | - SQL Server 2014 19 | - SQL Server 2016 20 | - Amazon RDS 21 | - Azure SQL DB 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | Files 2 | -------------------------------------------------------------------------------- /Articles/Backup/How to Build a SQL Server Disaster Recovery Plan with Google Compute Engine.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/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/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/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/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/Articles/Backup/Permissions_Poster_SQL_Server_2008_R2.pdf -------------------------------------------------------------------------------- /Articles/Backup/Permissions_Poster_SQL_Server_2012.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/Articles/Backup/Permissions_Poster_SQL_Server_2012.pdf -------------------------------------------------------------------------------- /Articles/Backup/Permissions_Poster_SQL_Server_2014.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/Articles/Backup/Permissions_Poster_SQL_Server_2014.pdf -------------------------------------------------------------------------------- /Articles/Backup/Permissions_Poster_SQL_Server_2016_and_SQLDB.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/Articles/Backup/Permissions_Poster_SQL_Server_2016_and_SQLDB.pdf -------------------------------------------------------------------------------- /Articles/Backup/Permissions_Poster_SQL_Server_vNext_and_SQLDB.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/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/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/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/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/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/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/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/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/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](http://www.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 | sp_configure 'clr enabled', 1; 19 | GO 20 | 21 | RECONFIGURE; 22 | GO 23 | ``` 24 | -------------------------------------------------------------------------------- /CLR/Regex/Fill_Factor/InstallRegex.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/CLR/Regex/Fill_Factor/InstallRegex.sql -------------------------------------------------------------------------------- /CLR/Regex/SqlRegularExpressions_SQLServerProject_QuickDeployment.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/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/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/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/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/Errors/Backup/CREATE DATABASE – I’ve not seen that before..maff -------------------------------------------------------------------------------- /Errors/Backup/Case study Troubleshooting Doomed Transactions.maff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/Errors/Backup/Case study Troubleshooting Doomed Transactions.maff -------------------------------------------------------------------------------- /Errors/Backup/Compressed backup errors and TF 3042.maff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/Errors/Backup/Compressed backup errors and TF 3042.maff -------------------------------------------------------------------------------- /Errors/Backup/Nuance of datetime data type in SQL Server.maff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/Errors/Backup/Nuance of datetime data type in SQL Server.maff -------------------------------------------------------------------------------- /Errors/Backup/SQL SERVER - Disabling 15000 Partitions (15k).maff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/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/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/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/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/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/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/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/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/Errors/Backup/SQL Server 2016 Online ALTER COLUMN Operation.maff -------------------------------------------------------------------------------- /Errors/Backup/Unable to restore a backup – Msg 3241.maff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/Errors/Backup/Unable to restore a backup – Msg 3241.maff -------------------------------------------------------------------------------- /Errors/Backup/Who owns your availability groups.maff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/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; -------------------------------------------------------------------------------- /Errors/regedit_sqlserver.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/Errors/regedit_sqlserver.png -------------------------------------------------------------------------------- /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/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/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/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/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/MonitorPageSplits.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Original link: http://sqlblog.com/blogs/jonathan_kehayias/archive/2010/10/17/tracking-page-splits-in-sql-server-denali-ctp1.aspx 3 | Author: Jonathan Kehayias 4 | */ 5 | 6 | IF (SELECT 1 FROM sys.server_event_sessions WHERE name = 'MonitorPageSplits') IS NOT NULL 7 | DROP EVENT SESSION MonitorPageSplits ON SERVER 8 | GO 9 | 10 | CREATE EVENT SESSION MonitorPageSplits ON SERVER 11 | ADD EVENT sqlserver.page_split 12 | ( 13 | ACTION (sqlserver.database_id, sqlserver.sql_text) 14 | WHERE sqlserver.database_id = 2 15 | ) 16 | ADD TARGET package0.ring_buffer 17 | WITH (MAX_DISPATCH_LATENCY = 1 SECONDS) 18 | GO 19 | 20 | ALTER EVENT SESSION MonitorPageSplits ON SERVER STATE = start; 21 | GO 22 | 23 | /* 24 | SELECT 25 | event_time = XEvent.value('(@timestamp)[1]','datetime') 26 | , orig_file_id = XEvent.value('(data[@name=''file_id'']/value)[1]','int') 27 | , orig_page_id = XEvent.value('(data[@name=''page_id'']/value)[1]','int') 28 | , database_id = XEvent.value('(data[@name=''database_id'']/value)[1]','int') 29 | , OBJECT_ID = p.OBJECT_ID 30 | , index_id = p.index_id 31 | , OBJECT_NAME = OBJECT_NAME(p.OBJECT_ID) 32 | , index_name = i.name 33 | , rowset_id = XEvent.value('(data[@name=''rowset_id'']/value)[1]','bigint') 34 | , splitOperation = XEvent.value('(data[@name=''splitOperation'']/text)[1]','varchar(255)') 35 | , new_page_file_id = XEvent.value('(data[@name=''new_page_file_id'']/value)[1]','int') 36 | , new_page_page_id = XEvent.value('(data[@name=''new_page_page_id'']/value)[1]','int') 37 | , sql_text = XEvent.value('(action[@name=''sql_text'']/value)[1]','varchar(max)') 38 | FROM 39 | ( 40 | SELECT CAST(target_data AS XML) AS target_data 41 | FROM sys.dm_xe_session_targets xst 42 | JOIN sys.dm_xe_sessions xs ON xs.address = xst.event_session_address 43 | WHERE xs.name = 'MonitorPageSplits' 44 | ) AS tab (target_data) 45 | CROSS APPLY target_data.nodes('/RingBufferTarget/event') AS EventNodes(XEvent) 46 | LEFT JOIN sys.allocation_units au 47 | ON au.container_id = XEvent.value('(data[@name=''rowset_id'']/value)[1]','bigint') 48 | LEFT JOIN sys.partitions p 49 | ON p.partition_id = au.container_id 50 | LEFT JOIN sys.indexes i 51 | ON p.OBJECT_ID = i.OBJECT_ID 52 | AND p.index_id = i.index_id 53 | 54 | -- View the Page allocations 55 | DBCC IND(tempdb, split_page, -1); 56 | */ 57 | -------------------------------------------------------------------------------- /Extended_Events/README.md: -------------------------------------------------------------------------------- 1 | # SQL Server Extended Events 2 | SQL Server Extended Events has a highly scalable and highly configurable architecture that allows users to collect as much or as little information as is necessary to troubleshoot or identify a performance problem. 3 | 4 | 5 | 6 | Useful links: 7 | - [Extended Events Microsoft Docs](https://docs.microsoft.com/en-us/sql/relational-databases/extended-events/extended-events) 8 | - [Find Your Dark Queries](http://michaeljswart.com/2017/04/finding-your-dark-queries/) 9 | - [Finding Blocked Processes and Deadlocks using SQL Server Extended Events](https://www.brentozar.com/archive/2014/03/extended-events-doesnt-hard/) 10 | - [What event information can I get by default from SQL Server?](http://dba.stackexchange.com/questions/48052/what-event-information-can-i-get-by-default-from-sql-server) 11 | - [Understanding the sql_text Action in Extended Events](https://www.sqlskills.com/blogs/jonathan/understanding-the-sql_text-action-in-extended-events/) 12 | - [Extended Events Series (1 of 31) – An Overview of Extended Events](https://www.sqlskills.com/blogs/jonathan/extended-events-overview/) 13 | - [Deep dive into the Extended Events Histogram target](https://www.sqlshack.com/deep-dive-into-the-extended-events-histogram-target/) 14 | - [Paul S. Randal articles about extended events](https://www.sqlskills.com/blogs/paul/category/extended-events/) 15 | - [Jonathan Kehayias articles about extended events](https://www.sqlskills.com/blogs/jonathan/category/extended-events/) 16 | - [Jonathan Kehayias extended 31 day series](https://www.sqlskills.com/blogs/jonathan/category/xevent-a-day-series/) 17 | - [Erin Stellato articles about extended events](https://www.sqlskills.com/blogs/erin/category/extended-events/) 18 | - [Stairway to SQL Server Extended Events](http://www.sqlservercentral.com/stairway/134867/) (by Erin Stellato) 19 | - [Measuring “Observer Overhead” of SQL Trace vs. Extended Events](https://sqlperformance.com/2012/10/sql-trace/observer-overhead-trace-extended-events) (by Jonathan Kehayias) 20 | 21 | Courses: 22 | - [SQL Server: Introduction to Extended Events](https://www.pluralsight.com/courses/sqlserver-basicxevents) (by Jonathan Kehayias) 23 | - [SQL Server: Advanced Extended Events](https://www.pluralsight.com/courses/sqlserver-advanced-xevents) (by Jonathan Kehayias) 24 | - [SQL Server: Replacing Profiler with Extended Events](https://www.pluralsight.com/courses/sqlserver-replacing-profiler-extended-events) (by Erin Stellato) 25 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | # The MIT License (MIT) 2 | 3 | Copyright (c) 2015-2017 Konstantin Taranov 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 10 | -------------------------------------------------------------------------------- /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/Export-AllPlans.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .SYNOPSIS 3 | Export all SQL Server query plans in files. 4 | .DESCRIPTION 5 | Export all plans from cache to a .SQLPLAN file 6 | .PARAMETR 7 | Machine - specify path to computer 8 | .PARAMETR 9 | SqlInstance - specify SQL Server instance name 10 | .PARAMETR 11 | DBname - specify database name 12 | .PARAMETR 13 | Output - specify path for exported files 14 | .EXAMPLE 15 | Export-AllPlans -Machine "hostname" 16 | .NOTES 17 | Requires: Powershell version 3 or higher, sqlps module 18 | Tested on: SQL Server 2014/2016 19 | Author: Grant Fritchey 20 | Author Modified: Alexandr Titenko 21 | Created date: 22 | Last modified: 2017-02-22 23 | #> 24 | 25 | function Export-AllPlans { 26 | 27 | param ( 28 | #Specify path to computer 29 | [Parameter(Mandatory=$false)] 30 | [String]$Machine = $env:COMPUTERNAME, 31 | #Specify SQL Server instance name 32 | [Parameter(Mandatory=$false)] 33 | [String]$SqlInstance = '', 34 | #Specify database name 35 | [Parameter(Mandatory=$false)] 36 | [String]$DBname = '', 37 | #Specify output files path 38 | [Parameter(Mandatory=$false)] 39 | [String]$Output = 'C:\plans' 40 | ) 41 | $Query = 'SELECT deqp.query_plan 42 | FROM sys.dm_exec_query_stats AS deqs 43 | CROSS APPLY sys.dm_exec_query_plan(deqs.plan_handle) AS deqp 44 | WHERE deqp.query_plan IS NOT NULL;' 45 | 46 | $SqlConnection = New-Object System.Data.SqlClient.SqlConnection 47 | $SqlConnection.ConnectionString = "Server=$Machine\$SqlInstance;Database=$DBname;trusted_connection=true" 48 | 49 | $PlanQuery = new-object System.Data.SqlClient.SqlCommand 50 | $PlanQuery.CommandText = $Query 51 | $PlanQuery.Connection = $SqlConnection 52 | $PlanAdapter = New-Object System.Data.SqlClient.SqlDataAdapter 53 | $PlanAdapter.SelectCommand = $PlanQuery 54 | $PlanSet = new-object System.Data.DataSet 55 | $PlanAdapter.Fill($PlanSet) 56 | 57 | foreach($row in $PlanSet.Tables[0]) 58 | { 59 | $i+=1 60 | $row[0] | Out-File -FilePath "$Output\$i.sqlplan" 61 | } 62 | } 63 | 64 | Export-AllPlans -------------------------------------------------------------------------------- /PowerShell/Fast_table_to_csv.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .SYNOPSIS 3 | . 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 | $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/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 | -------------------------------------------------------------------------------- /PowerShell/Truncate-AllTables.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .SYNOPSIS 3 | Truncate all tables in database. 4 | .DESCRIPTION 5 | Truncate all tables in database. Drop and recreate all foreign keys. 6 | .PARAMETR 7 | Machine - specify path to computer 8 | .PARAMETR 9 | SqlInstance - specify SQL Server instance name 10 | .PARAMETR 11 | DBname - specify database name 12 | .EXAMPLE 13 | Truncate-AllTables -Machine "hostname" 14 | .NOTES 15 | Requires: Powershell version 3 or higher, sqlps module 16 | Tested on: SQL Server 2014/2016 17 | Author: Jeffrey Yao 18 | Author Modified: Alexandr Titenko 19 | Created date: 2016-03-15 20 | Last modified: 2017-02-16 21 | #> 22 | 23 | function Truncate-AllTables { 24 | 25 | param ( 26 | #Specify path to computer 27 | [Parameter(Mandatory=$false)] 28 | [String]$Machine = $env:COMPUTERNAME, 29 | #Specify SQL Server instance name 30 | [Parameter(Mandatory=$false)] 31 | [String]$SqlInstance = 'default', 32 | #Specify database name 33 | [Parameter(Mandatory=$false)] 34 | [String]$DBname = 'DBName' 35 | ) 36 | import-module sqlps -DisableNameChecking; 37 | set-location c:\; 38 | Write-Host "[*] Start at $(Get-Date -Format 'HH.mm.ss')" -foreground:yellow 39 | $sw = [Diagnostics.Stopwatch]::StartNew() 40 | 41 | [String]$FT_index=''; 42 | 43 | [Microsoft.SqlServer.Management.Smo.Database]$db = get-item "sqlserver:\sql\$Machine\$SqlInstance\databases\$($DBname)"; 44 | $db.tables.Refresh(); 45 | 46 | #script out FKs and save it to variable $fk_script 47 | $db.tables | % -begin {[string]$fk_script=''} -process {$_.foreignkeys.refresh(); $_.foreignkeys | % {$fk_script +=$_.script() +";`r`n"} } 48 | 49 | #drop foreign keys 50 | $db.tables | % -begin {$fks=@()} -process { $fks += $_.ForeignKeys }; 51 | foreach ($fk in $fks) {$fk.drop();} 52 | 53 | foreach ($t in $db.tables ) 54 | { 55 | $t.TruncateData(); #direct truncate 56 | write-host "truncate table [$($t.Schema)].[$($t.name)]" -ForegroundColor yellow 57 | } 58 | 59 | #resetup the FKs 60 | $db.ExecuteNonQuery($fk_script); 61 | $db = $null; 62 | $svr = $null; 63 | 64 | Write-Host "[*] Finish at $(Get-Date -Format 'HH.mm.ss')" -foreground:yellow 65 | Write-Host "Duration:" 66 | $sw.Stop(); 67 | $sw.Elapsed | Format-Table -Property Minutes, Seconds, Milliseconds -AutoSize; 68 | } 69 | 70 | Truncate-AllTables -------------------------------------------------------------------------------- /PowerShell/When-SQL-Serve-was-Rebooted.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .SYNOPSIS 3 | When SQL Server was rebooted 4 | .DESCRIPTION 5 | Sets Extended Events Sessions to Auto-Start and starts it if it is not running 6 | .EXAMPLE 7 | ./When-SQL-Serve-was-Rebooted.ps1 8 | .LINK 9 | Script posted over: 10 | https://simplesqlserver.com/2016/06/01/powershell-when-were-my-servers-rebooted/ 11 | .NOTES 12 | Author: Steve Hood 13 | Created Date: 2016-06-01 14 | #> 15 | 16 | Import-Module ActiveDirectory 17 | 18 | #either method works for getting a list of groups. You can type in all of your groups or make a query to find them all. 19 | #$groups = "Test SQL Servers", "Prod SQL Servers 1", "Prod SQL Servers 2", "SQL Cluster Servers 1", "SQL Cluster Servers 2" 20 | 21 | $groups = Get-ADGroup -Filter {name -like "*SQL *"} | where-object {$_.distinguishedname -like "*OU=SUS Group*"} 22 | 23 | ForEach ($group in $groups) { 24 | $computerlist = Get-ADGroupMember $group -Recursive | SELECT name 25 | 26 | #If there were any computers in the list, do this. It skips empty groups. 27 | if ($computerlist) { 28 | $computerlistcount = $computerlist.Count 29 | 30 | #It returns an object instead of an array if there was only one, so count would be null 31 | if (!$computerlistcount) { 32 | $computerlistcount = 1 33 | } 34 | 35 | Write-Host "" 36 | Write-Host "$computerlistcount server(s) in" $group.name 37 | } 38 | 39 | ForEach ($computer in $computerlist) { 40 | try { 41 | Get-WmiObject win32_operatingsystem -ComputerName $computer.name -ErrorAction Stop | select csname, @{LABEL='LastBootUpTime';EXPRESSION={$_.ConverttoDateTime($_.lastbootuptime)}} 42 | } 43 | catch { 44 | #This logic is lacking. I don't care what error you got, just say you couldn't connect and we'll move on. 45 | #For this script, it probably means the server is in the middle of a reboot 46 | Write-Host "Could not connect to" $computer.name 47 | Continue 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /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/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/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/Create Numbers Table.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 | Create Numbers table 13 | 14 | Creates a numbers table and populates it with 10000 rows. 15 | Matan Yungman 16 | 17 | Expansion 18 | 19 |
20 | 21 | 22 | 23 | NumbersTableName 24 | Name of the numbers table 25 | #Numbers 26 | 27 | 28 | TempTableName 29 | Name of the temporary table 30 | #T 31 | 32 | 33 | 34 | 35 | 48 | 49 | 50 |
51 |
52 | -------------------------------------------------------------------------------- /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/24_SSMS_command-line_parameters.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/SSMS/SSMS_Tips/24_SSMS_command-line_parameters.png -------------------------------------------------------------------------------- /SSMS/SSMS_Tips/24_changing_what_ssms_opens_on_startup.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/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/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/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/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/SSMS/SSMS_Tips/24_create_solution_commonly_used_sql_scripts.gif -------------------------------------------------------------------------------- /SSMS/SSMS_Tips/25_query_execution_options.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/SSMS/SSMS_Tips/25_query_execution_options.png -------------------------------------------------------------------------------- /SSMS/SSMS_Tips/25_query_execution_options_ansi.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/SSMS/SSMS_Tips/25_query_execution_options_ansi.png -------------------------------------------------------------------------------- /SSMS/SSMS_Tips/26_sql_server_diagnostics_extension.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/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/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/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/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/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/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/SSMS/SSMS_Tips/29_SSMS_Database_Default_Reports.png -------------------------------------------------------------------------------- /SSMS/SSMS_Tips/29_SSMS_Server_Default_Reports.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/SSMS/SSMS_Tips/29_SSMS_Server_Default_Reports.png -------------------------------------------------------------------------------- /SSMS/SSMS_Tips/32_object_explore_details_01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/SSMS/SSMS_Tips/32_object_explore_details_01.png -------------------------------------------------------------------------------- /SSMS/SSMS_Tips/32_object_explore_details_02.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/SSMS/SSMS_Tips/32_object_explore_details_02.png -------------------------------------------------------------------------------- /SSMS/SSMS_Tips/32_object_explore_details_03.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/SSMS/SSMS_Tips/32_object_explore_details_03.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/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/SSMS/SSMS_Tips/SQL_Vulnerability_Assessment.gif -------------------------------------------------------------------------------- /SSMS/SSMS_Tips/additional_connection_parameters.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/SSMS/SSMS_Tips/additional_connection_parameters.png -------------------------------------------------------------------------------- /SSMS/SSMS_Tips/disable_copy_of_empty_text.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/SSMS/SSMS_Tips/disable_copy_of_empty_text.png -------------------------------------------------------------------------------- /SSMS/SSMS_Tips/import_and_export_settings.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/SSMS/SSMS_Tips/import_and_export_settings.png -------------------------------------------------------------------------------- /SSMS/SSMS_Tips/keyboard_shortcuts_for_stored_procedures.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/SSMS/SSMS_Tips/keyboard_shortcuts_for_stored_procedures.png -------------------------------------------------------------------------------- /SSMS/SSMS_Tips/splitting_the_query_window.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/SSMS/SSMS_Tips/splitting_the_query_window.gif -------------------------------------------------------------------------------- /SSMS/SSMS_Tips/ssms_script_objects.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/SSMS/SSMS_Tips/ssms_script_objects.gif -------------------------------------------------------------------------------- /SSMS/SSMS_Tips/undock_tabs_and_windows_for_multi_monitor_support.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/SSMS/SSMS_Tips/undock_tabs_and_windows_for_multi_monitor_support.gif -------------------------------------------------------------------------------- /SSMS/SSMS_Tips/working_with_tabs_headers.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/SSMS/SSMS_Tips/working_with_tabs_headers.png -------------------------------------------------------------------------------- /SSMS/SSMS_vssettings/AB.DarkScheme.LargeFonts.vssettings: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 2 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /SSMS/SSMS_vssettings/AB.DarkScheme.NormalFonts.vssettings: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 2 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /SSMS/SSMS_vssettings/README.md: -------------------------------------------------------------------------------- 1 | # SSMS settings files 2 | 3 | - [NewSettings_17.2(14.0.17177).vssettings](/NewSettings_17.2(14.0.17177).vssettings) 4 | - [NewSettings_2014(12.0.5556).vssettings](/NewSettings_2014(12.0.5556).vssettings) 5 | - [NewSettings_Default_17.2(14.0.17177).vssettings](/NewSettings_Default_17.2(14.0.17177).vssettings) 6 | - [NewSettings_Default_2014(12.0.5556).vssettings](/NewSettings_Default_2014(12.0.5556).vssettings) 7 | -------------------------------------------------------------------------------- /Scripts/Azure SQL Database Diagnostic Information Queries.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/Scripts/Azure SQL Database Diagnostic Information Queries.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/Blocked_Session.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Kenneth Fisher 3 | Original link: https://sqlstudies.com/2017/01/18/lead-blocker/ 4 | */ 5 | WITH Blocked_Sessions AS ( 6 | -- Collect lead blockers 7 | -- Pull all blocking IDs & check which ones are not being blocked themselves 8 | SELECT sys.dm_exec_requests.blocking_session_id AS lead_session_id, 9 | sys.dm_exec_requests.blocking_session_id AS blocking_session_id , 0 Cnt 10 | FROM sys.dm_exec_requests 11 | WHERE blocking_session_id <> 0 12 | AND blocking_session_id NOT IN (SELECT session_id 13 | FROM sys.dm_exec_requests 14 | WHERE sys.dm_exec_requests.blocking_session_id <> 0) 15 | UNION ALL 16 | -- Recurse through list of blocked sessions 17 | SELECT Blocked_Sessions.lead_session_id, sys.dm_exec_requests.session_id, 1 Cnt 18 | FROM sys.dm_exec_requests 19 | JOIN Blocked_Sessions 20 | ON Blocked_Sessions.blocking_session_id = sys.dm_exec_requests.blocking_session_id 21 | ), 22 | Blocked AS ( 23 | -- Add up all sessions blocked for the lead blocker 24 | SELECT lead_session_id, SUM(Cnt) AS sessions_blocked 25 | FROM Blocked_Sessions 26 | GROUP BY lead_session_id) 27 | SELECT Blocked.*, DATEDIFF(s, Sess.last_request_start_time, getdate()) seconds_blocking, 28 | ISNULL(Req.status,'sleeping') [status], SqlText.text [sql_text], 29 | STUFF((SELECT DISTINCT ISNULL(', ' + db.name,'') 30 | FROM sys.databases db 31 | JOIN sys.dm_tran_locks lcks 32 | ON db.database_id = lcks.resource_database_id 33 | WHERE lcks.request_session_id = Sess.session_id 34 | ORDER BY ISNULL(', ' + db.name,'') 35 | FOR XML PATH(''),TYPE).value('.','VARCHAR(MAX)') 36 | ,1,2,'') AS database_list 37 | , Conn.client_net_address, Sess.login_name 38 | FROM sys.dm_exec_connections Conn 39 | LEFT OUTER JOIN sys.dm_exec_sessions Sess 40 | ON Conn.session_id = Sess.session_id 41 | JOIN Blocked 42 | ON Blocked.lead_session_id = Sess.session_id 43 | CROSS APPLY sys.dm_exec_sql_text(Conn.most_recent_sql_handle) SqlText 44 | LEFT JOIN sys.dm_exec_requests Req 45 | ON Req.session_id = Sess.session_id 46 | WHERE Blocked.sessions_blocked >= 1 47 | -- We only care if the session has been blocked for longer than 30 seconds. 48 | -- This can obviously be modified or commented out. 49 | AND DATEDIFF(s, Sess.last_request_start_time, getdate()) > 30; 50 | -------------------------------------------------------------------------------- /Scripts/BufferPoolExtension.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Author:Ryan Adams 3 | Original link: http://www.ryanjadams.com/2017/05/implementing-buffer-pool-extension 4 | */ 5 | 6 | --Review current BPE configuration 7 | SELECT [path], state_description, current_size_in_kb, 8 | CAST(current_size_in_kb/1048576.0 AS DECIMAL(10,2)) AS [Size (GB)] 9 | FROM sys.dm_os_buffer_pool_extension_configuration; 10 | 11 | --Reduce SQL Server Max memory to restrict the BP and force the use of BPE 12 | EXEC sys.sp_configure 'show advanced options', '1' RECONFIGURE WITH OVERRIDE; 13 | GO 14 | EXEC sys.sp_configure 'max server memory (MB)', '2000'; 15 | GO 16 | RECONFIGURE WITH OVERRIDE; 17 | GO 18 | EXEC sys.sp_configure 'show advanced options', '0' RECONFIGURE WITH OVERRIDE; 19 | GO 20 | /*********** WE HAVE TO RESTART SQL SERVER FOR BPE TO SEE THE RAM CHANGE ***************/ 21 | 22 | --Enable BPE 23 | --Go look at the file size on disk right after you run this 24 | ALTER SERVER CONFIGURATION 25 | SET BUFFER POOL EXTENSION ON (FILENAME = 'C:\Temp\BP_Extension.BPE', SIZE = 2 GB); 26 | 27 | --Now that it is enabled we'll inspect the configuration again 28 | SELECT [path], state_description, current_size_in_kb, 29 | CAST(current_size_in_kb/1048576.0 AS DECIMAL(10,2)) AS [Size (GB)] 30 | FROM sys.dm_os_buffer_pool_extension_configuration; 31 | 32 | --Try to read enough data to fill BP and start using BPE 33 | USE AdventureworksDW2016CTP3; 34 | GO 35 | SELECT * FROM dbo.FactResellerSalesXL_PageCompressed; 36 | --If the above didn't do the trick then query this table as well 37 | --SELECT * FROM dbo.FactResellerSalesXL_CCI; 38 | 39 | --Let's see what went to BPE. If there are no results then go query more data. 40 | SELECT DB_NAME(database_id) AS [Database Name], COUNT(page_id) AS [Page Count], 41 | CAST(COUNT(*)/128.0 AS DECIMAL(10, 2)) AS [Buffer size(MB)], 42 | AVG(read_microsec) AS [Avg Read Time (microseconds)] 43 | FROM sys.dm_os_buffer_descriptors 44 | WHERE database_id <> 32767 45 | AND is_in_bpool_extension = 1 46 | GROUP BY DB_NAME(database_id) 47 | ORDER BY [Buffer size(MB)] DESC; 48 | 49 | --Turn BPE off. Go look in c:\temp to see what happens to the physical data file 50 | ALTER SERVER CONFIGURATION 51 | SET BUFFER POOL EXTENSION OFF; 52 | 53 | --Put Max Server Memory back where it was 54 | EXEC sys.sp_configure 'show advanced options', '1' RECONFIGURE WITH OVERRIDE; 55 | GO 56 | EXEC sys.sp_configure 'max server memory (MB)', '3500'; 57 | GO 58 | RECONFIGURE WITH OVERRIDE; 59 | GO 60 | EXEC sys.sp_configure 'show advanced options', '0' RECONFIGURE WITH OVERRIDE; 61 | GO -------------------------------------------------------------------------------- /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/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/Date_Format_Cheat_Sheet.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Aaron Bertrand 3 | Original links: https://www.mssqltips.com/sqlservertip/4052/build-a-cheat-sheet-for-sql-server-date-and-time-formats/ 4 | */ 5 | 6 | SET NOCOUNT ON; 7 | 8 | DECLARE @sql NVARCHAR(MAX), @v VARCHAR(30), @d DATETIME2(7), @sqlServerMajorVersion TINYINT; 9 | SET @sql = N''; 10 | 11 | -- a random date/time, making sure no single digits for any 12 | -- date parts as these can truncate length of output: 13 | SET @d = '2015-12-31T22:25:59.7901245'; 14 | 15 | SET @sqlServerMajorVersion = CAST(SERVERPROPERTY ('ProductMajorVersion') AS TINYINT); 16 | 17 | CREATE TABLE #s(style VARCHAR(3)); 18 | 19 | -- for SQL Server < 2012 20 | IF @sqlServerMajorVersion < 12 21 | BEGIN 22 | 23 | DECLARE @s INT = 0; 24 | WHILE @s <= 255 25 | BEGIN 26 | BEGIN TRY 27 | SET @sql = N'SELECT @v = CONVERT(VARCHAR(30), @d, ' + RTRIM(@s) + ');'; 28 | EXEC sys.sp_executesql @sql, N'@v VARCHAR(30), @d DATETIME2(7)', @v, @d; 29 | INSERT #s(style) VALUES(@s); 30 | END TRY 31 | BEGIN CATCH 32 | SET @sql = N''; 33 | END CATCH 34 | SET @s = @s + 1; 35 | END 36 | END 37 | 38 | -- for SQL Server >= 2012 39 | ELSE 40 | BEGIN 41 | SET @sql = N''; 42 | 43 | WITH x(rn) AS 44 | ( 45 | SELECT TOP (256) CONVERT(VARCHAR(3), ROW_NUMBER() OVER (ORDER BY name) - 1) 46 | FROM sys.all_objects ORDER BY name 47 | ) 48 | SELECT @sql = @sql + N'INSERT #s SELECT ' + rn + ' FROM 49 | (SELECT n = TRY_CONVERT(VARCHAR(30),@d,' + rn + ')) AS x 50 | WHERE n IS NOT NULL;' FROM x; 51 | 52 | EXEC sys.sp_executesql @sql, N'@d DATETIME2(7)', @d; 53 | END 54 | 55 | 56 | SET @sql = N''; 57 | 58 | SELECT @sql = @sql + N' UNION ALL SELECT [style #] = ' 59 | + style + ', expression = N''CONVERT(CHAR('' 60 | +RTRIM(LEN(CONVERT(VARCHAR(30), @d, ' + style + '))) 61 | +''), @d, ' + style + ')'', 62 | [output] = CONVERT(VARCHAR(30), @d, ' + style + ')' 63 | FROM #s; 64 | 65 | SET @sql = STUFF(@sql, 1, 11, N'') + N';'; 66 | 67 | EXEC sys.sp_executesql @sql, N'@d DATETIME2(7)', @d; 68 | 69 | DROP TABLE #s; 70 | -------------------------------------------------------------------------------- /Scripts/DetermineSpaceWithinSQLDatabaseFiles.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Author: BradC 3 | Original link: https://dba.stackexchange.com/questions/7917/how-to-determine-used-free-space-within-sql-database-files 4 | Desctiption: Determine used/free space within SQL database files 5 | */ 6 | 7 | 8 | --This one works for me and seems to be consistent on SQL 2000 to SQL Server 2012 CTP3: 9 | SELECT RTRIM(name) AS [Segment Name], groupid AS [Group Id], filename AS [File Name], 10 | CAST(size/128.0 AS DECIMAL(10,2)) AS [Allocated Size in MB], 11 | CAST(FILEPROPERTY(name, 'SpaceUsed')/128.0 AS DECIMAL(10,2)) AS [Space Used in MB], 12 | CAST([maxsize]/128.0 AS DECIMAL(10,2)) AS [Max in MB], 13 | CAST([maxsize]/128.0-(FILEPROPERTY(name, 'SpaceUsed')/128.0) AS DECIMAL(10,2)) AS [Available Space in MB], 14 | CAST((CAST(FILEPROPERTY(name, 'SpaceUsed')/128.0 AS DECIMAL(10,2))/CAST([maxsize]/128.0 AS DECIMAL(10,2)))*100 AS DECIMAL(10,2)) AS [Percent Used] 15 | FROM sysfiles 16 | ORDER BY groupid DESC 17 | 18 | 19 | --An alternative (not compatible with SQL Server 200) that provides more information, suggested by Tri Effendi SS: 20 | USE [database name] 21 | GO 22 | SELECT 23 | [TYPE] = A.TYPE_DESC 24 | ,[FILE_Name] = A.name 25 | ,[FILEGROUP_NAME] = fg.name 26 | ,[File_Location] = A.PHYSICAL_NAME 27 | ,[FILESIZE_MB] = CONVERT(DECIMAL(10,2),A.SIZE/128.0) 28 | ,[USEDSPACE_MB] = CONVERT(DECIMAL(10,2),A.SIZE/128.0 - ((SIZE/128.0) - CAST(FILEPROPERTY(A.NAME, 'SPACEUSED') AS INT)/128.0)) 29 | ,[FREESPACE_MB] = CONVERT(DECIMAL(10,2),A.SIZE/128.0 - CAST(FILEPROPERTY(A.NAME, 'SPACEUSED') AS INT)/128.0) 30 | ,[FREESPACE_%] = CONVERT(DECIMAL(10,2),((A.SIZE/128.0 - CAST(FILEPROPERTY(A.NAME, 'SPACEUSED') AS INT)/128.0)/(A.SIZE/128.0))*100) 31 | ,[AutoGrow] = 'By ' + CASE is_percent_growth WHEN 0 THEN CAST(growth/128 AS VARCHAR(10)) + ' MB -' 32 | WHEN 1 THEN CAST(growth AS VARCHAR(10)) + '% -' ELSE '' END 33 | + CASE max_size WHEN 0 THEN 'DISABLED' WHEN -1 THEN ' Unrestricted' 34 | ELSE ' Restricted to ' + CAST(max_size/(128*1024) AS VARCHAR(10)) + ' GB' END 35 | + CASE is_percent_growth WHEN 1 THEN ' [autogrowth by percent, BAD setting!]' ELSE '' END 36 | FROM sys.database_files A LEFT JOIN sys.filegroups fg ON A.data_space_id = fg.data_space_id 37 | order by A.TYPE desc, A.NAME; -------------------------------------------------------------------------------- /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/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_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/Find_Synonyms_for_nested_objects_in_the_same_database.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Svetlana Golovko 3 | Source link: https://www.mssqltips.com/sqlservertip/4876/finding-sql-server-object-dependencies-for-synonyms/ 4 | */ 5 | 6 | DECLARE @schema SYSNAME; 7 | 8 | -- find default user's schema for the one-part base objects names (no schema name) 9 | SELECT @schema = default_schema_name 10 | FROM sys.database_principals 11 | WHERE name = user_name(); 12 | 13 | -- find all views with their dependencies 14 | WITH DepTree 15 | AS 16 | ( 17 | SELECT o.[name], 18 | s.[name] AS oSchema, 19 | o.[object_id] AS referenced_id , 20 | o.[name] AS referenced_name, 21 | o.[object_id] AS referencing_id, 22 | o.[name] AS referencing_name, 23 | 0 AS NestLevel 24 | FROM sys.objects o JOIN sys.schemas s 25 | ON o.[schema_id] = s.[schema_id] 26 | WHERE o.is_ms_shipped = 0 27 | -- comment out next line if you need to check all object types, not only views 28 | AND o.[type] = 'V' 29 | 30 | UNION ALL 31 | 32 | SELECT r.[name], 33 | r.oSchema, 34 | d1.referenced_id, 35 | OBJECT_NAME( d1.referenced_id) , 36 | d1.referencing_id, 37 | OBJECT_NAME( d1.referencing_id) , 38 | NestLevel + 1 39 | FROM sys.sql_expression_dependencies d1 JOIN DepTree r 40 | ON d1.referenced_id = r.referencing_id 41 | ) 42 | , 43 | -- find all synonyms in CURRENT database 44 | Syn 45 | AS 46 | ( 47 | SELECT [name], 48 | base_object_name, 49 | LTRIM(RTRIM( REPLACE(REPLACE(REPLACE(REPLACE(base_object_name ,'[',''),']',''), DB_NAME()+'..',''), DB_NAME()+'.',''))) as objectname 50 | FROM sys.synonyms s 51 | WHERE (base_object_name like '%.%.%' 52 | AND LEFT (REPLACE(REPLACE(base_object_name ,'[',''),']',''), 53 | CHARINDEX('.', REPLACE(REPLACE(base_object_name ,'[',''),']',''))-1) = DB_NAME()) 54 | OR base_object_name NOT LIKE '%.%.%' 55 | ) 56 | 57 | SELECT s.[name] AS syn_name, 58 | base_object_name AS syn_base_object, 59 | MAX(NestLevel) AS nest_level 60 | FROM DepTree t JOIN Syn s 61 | ON oSchema + '.' + t.referencing_name = 62 | CASE WHEN s.objectname NOT LIKE '%.%' THEN @schema + '.' + s.objectname 63 | ELSE s.objectname END 64 | GROUP BY base_object_name, s.[name] 65 | -- comment out next line if you want to see all synonyms' dependent objects regardless nest level 66 | HAVING MAX(NestLevel) > 2 67 | ORDER BY MAX(NestLevel) DESC; 68 | GO 69 | -------------------------------------------------------------------------------- /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/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_Restore_Script_From_Backup_Folder.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Greg Robidoux 3 | Original link: https://www.mssqltips.com/sqlservertip/1584/auto-generate-sql-server-restore-script-from-backup-files-in-a-directory/ 4 | */ 5 | 6 | USE Master; 7 | GO 8 | SET NOCOUNT ON; 9 | 10 | -- 1 - Variable declaration 11 | DECLARE @dbName sysname; 12 | DECLARE @backupPath NVARCHAR(500); 13 | DECLARE @cmd NVARCHAR(500); 14 | DECLARE @fileList TABLE (backupFile NVARCHAR(255)); 15 | DECLARE @lastFullBackup NVARCHAR(500); 16 | DECLARE @lastDiffBackup NVARCHAR(500); 17 | DECLARE @backupFile NVARCHAR(500); 18 | 19 | -- 2 - Initialize variables 20 | SET @dbName = 'Customer'; 21 | SET @backupPath = 'D:\SQLBackups\'; 22 | 23 | -- 3 - get list of files 24 | SET @cmd = 'DIR /b ' + @backupPath; 25 | 26 | INSERT INTO @fileList(backupFile) 27 | EXEC master.sys.xp_cmdshell @cmd; 28 | 29 | -- 4 - Find latest full backup 30 | SELECT @lastFullBackup = MAX(backupFile) 31 | FROM @fileList 32 | WHERE backupFile LIKE '%.BAK' 33 | AND backupFile LIKE @dbName + '%'; 34 | 35 | SET @cmd = 'RESTORE DATABASE ' + @dbName + ' FROM DISK = ''' 36 | + @backupPath + @lastFullBackup + ''' WITH NORECOVERY, REPLACE'; 37 | PRINT @cmd; 38 | 39 | -- 4 - Find latest diff backup 40 | SELECT @lastDiffBackup = MAX(backupFile) 41 | FROM @fileList 42 | WHERE backupFile LIKE '%.DIF' 43 | AND backupFile LIKE @dbName + '%' 44 | AND backupFile > @lastFullBackup; 45 | 46 | -- check to make sure there is a diff backup 47 | IF @lastDiffBackup IS NOT NULL 48 | BEGIN 49 | SET @cmd = 'RESTORE DATABASE ' + @dbName + ' FROM DISK = ''' 50 | + @backupPath + @lastDiffBackup + ''' WITH NORECOVERY'; 51 | PRINT @cmd; 52 | SET @lastFullBackup = @lastDiffBackup; 53 | END 54 | 55 | -- 5 - check for log backups 56 | DECLARE backupFiles CURSOR FOR 57 | SELECT backupFile 58 | FROM @fileList 59 | WHERE backupFile LIKE '%.TRN' 60 | AND backupFile LIKE @dbName + '%' 61 | AND backupFile > @lastFullBackup; 62 | 63 | OPEN backupFiles 64 | 65 | -- Loop through all the files for the database 66 | FETCH NEXT FROM backupFiles INTO @backupFile 67 | 68 | WHILE @@FETCH_STATUS = 0 69 | BEGIN 70 | SET @cmd = 'RESTORE LOG ' + @dbName + ' FROM DISK = ''' 71 | + @backupPath + @backupFile + ''' WITH NORECOVERY'; 72 | PRINT @cmd; 73 | FETCH NEXT FROM backupFiles INTO @backupFile; 74 | END 75 | 76 | CLOSE backupFiles; 77 | DEALLOCATE backupFiles; 78 | 79 | -- 6 - put database in a useable state 80 | SET @cmd = 'RESTORE DATABASE ' + @dbName + ' WITH RECOVERY'; 81 | PRINT @cmd; -------------------------------------------------------------------------------- /Scripts/Generate_table_definition_to_match_query.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Author: SQL Undercover 3 | Source link: https://sqlundercover.com/2017/08/21/undercover-toolbox-generate-a-temporary-table-definition-to-match-the-resultset-of-a-query/ 4 | */ 5 | 6 | SET NOCOUNT ON; 7 | 8 | DECLARE @Query VARCHAR(MAX) = 'select * from sys.databases;'; 9 | DECLARE @TempTableName VARCHAR(128) = '#temptable'; 10 | DECLARE @ColumnList VARCHAR(MAX); 11 | 12 | SELECT @ColumnList = STUFF((SELECT ',' + name + ' ' + system_type_name + ' ' + 13 | CASE is_nullable WHEN 0 THEN 'NOT NULL' ELSE 'NULL' END 14 | + CHAR(10) 15 | FROM sys.dm_exec_describe_first_result_set(@Query, NULL, 0) 16 | FOR XML PATH('')) ,1,1,''); 17 | 18 | PRINT 'CREATE TABLE ' + @TempTableName + '(' 19 | PRINT @ColumnList; 20 | PRINT(')'); -------------------------------------------------------------------------------- /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_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_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/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/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/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/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/Scripts/Monitor_Deadlocks_with_Extended_Events.sql -------------------------------------------------------------------------------- /Scripts/Move_tempdb.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Brent Ozar 3 | Original link: https://www.brentozar.com/archive/2017/11/move-tempdb-another-drive-folder/ 4 | */ 5 | 6 | SELECT 'ALTER DATABASE tempdb MODIFY FILE (NAME = [' + f.name + '],' 7 | + ' FILENAME = ''Z:\MSSQL\DATA\' + f.name 8 | + CASE WHEN f.type = 1 THEN '.ldf' ELSE '.mdf' END 9 | + ''');' 10 | FROM sys.master_files f 11 | WHERE f.database_id = DB_ID(N'tempdb'); 12 | -------------------------------------------------------------------------------- /Scripts/ObjectSizes.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Author: @DBA_ANDY 3 | Original link: http://nebraskasql.blogspot.ru/2017/07/toolbox-which-tables-are-using-all-of.html 4 | Desctiption: Which Tables are Using All of My Space? 5 | */ 6 | 7 | /* 8 | Object Sizes 9 | Modified from http://stackoverflow.com/questions/15896564/get-table-and-index-storage-size-in-sql-server 10 | */ 11 | SELECT TOP 50 12 | @@SERVERNAME as InstanceName 13 | , DB_NAME() as DatabaseName 14 | , s.NAME AS SchemaName 15 | , t.NAME AS TableName 16 | , SUM(p.rows) AS RowCounts 17 | --, SUM(a.total_pages) * 8 AS TotalSpaceKB 18 | , SUM(a.total_pages) * 8/1024.0 AS TotalSpaceMB 19 | , SUM(a.total_pages) * 8/1024.0/1024.0 AS TotalSpaceGB 20 | , SUM(a.used_pages) * 8/1024.0 AS UsedSpaceMB 21 | , (SUM(a.total_pages) - SUM(a.used_pages)) * 8/1024.0 AS UnusedSpaceMB 22 | FROM sys.tables t 23 | INNER JOIN sys.schemas s 24 | ON s.schema_id = t.schema_id 25 | INNER JOIN sys.indexes i 26 | ON t.OBJECT_ID = i.object_id 27 | INNER JOIN sys.partitions p 28 | ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id 29 | INNER JOIN sys.allocation_units a 30 | ON p.partition_id = a.container_id 31 | WHERE t.NAME NOT LIKE 'dt%' -- filter out system tables for diagramming 32 | AND t.is_ms_shipped = 0 33 | AND i.OBJECT_ID > 255 34 | GROUP BY t.Name 35 | , s.Name 36 | ORDER BY TotalSpaceMB DESC 37 | -------------------------------------------------------------------------------- /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/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/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/Ring_Bufer_Analyze.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Dmitriy Ivanov 3 | Original link: https://t.me/sqlcom 4 | */ 5 | 6 | WITH RingBufferXML 7 | AS(SELECT CAST(Record AS XML) AS RBR FROM sys .dm_os_ring_buffers 8 | WHERE ring_buffer_type = 'RING_BUFFER_RESOURCE_MONITOR' 9 | ) 10 | SELECT DISTINCT 'Problems' = 11 | CASE 12 | WHEN XMLRecord.value('(ResourceMonitor/IndicatorsProcess)[1]','tinyint') = 0 AND 13 | XMLRecord.value('(ResourceMonitor/IndicatorsSystem)[1]','tinyint') = 2 14 | THEN 'Insufficient physical memory for the system' 15 | WHEN XMLRecord.value('(ResourceMonitor/IndicatorsProcess)[1]','tinyint') = 0 AND 16 | XMLRecord.value('(ResourceMonitor/IndicatorsSystem)[1]','tinyint') = 4 17 | THEN 'Insufficient virtual memory for the system' 18 | WHEN XMLRecord.value('(ResourceMonitor/IndicatorsProcess)[1]', 'tinyint') = 2 AND 19 | XMLRecord.value('(ResourceMonitor/IndicatorsSystem)[1]','tinyint') = 0 20 | THEN'Insufficient physical memory for queries' 21 | WHEN XMLRecord.value('(ResourceMonitor/IndicatorsProcess)[1]', 'tinyint') = 4 AND 22 | XMLRecord.value('(ResourceMonitor/IndicatorsSystem)[1]', 'tinyint') = 4 23 | THEN 'Insufficient virtual memory for queries and system' 24 | WHEN XMLRecord.value('(ResourceMonitor/IndicatorsProcess)[1]','tinyint') = 2 AND 25 | XMLRecord.value('(ResourceMonitor/IndicatorsSystem)[1]','tinyint') = 4 26 | THEN 'Insufficient virtual memory for the system and physical for queries' 27 | WHEN XMLRecord.value('(ResourceMonitor/IndicatorsProcess)[1]', 'tinyint') = 2 AND 28 | XMLRecord.value('(ResourceMonitor/IndicatorsSystem)[1]', 'tinyint') = 2 29 | THEN 'There is not enough physical memory for the system and requests' 30 | END 31 | FROM RingBufferXML 32 | CROSS APPLY RingBufferXML.RBR.nodes ('Record') Record (XMLRecord) 33 | WHERE XMLRecord.value('(ResourceMonitor/IndicatorsProcess)[1]','tinyint') IN (0,2,4) AND 34 | XMLRecord.value('(ResourceMonitor/IndicatorsSystem)[1]' ,'tinyint') IN (0,2,4) AND 35 | XMLRecord.value('(ResourceMonitor/IndicatorsProcess)[1]','tinyint') + 36 | XMLRecord.value('(ResourceMonitor/IndicatorsSystem)[1]' ,'tinyint') > 0; 37 | -------------------------------------------------------------------------------- /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 Server 2005 Diagnostic Information Queries.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/Scripts/SQL Server 2005 Diagnostic Information Queries.sql -------------------------------------------------------------------------------- /Scripts/SQL Server 2008 Diagnostic Information Queries.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/Scripts/SQL Server 2008 Diagnostic Information Queries.sql -------------------------------------------------------------------------------- /Scripts/SQL Server 2008 R2 Diagnostic Information Queries.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/Scripts/SQL Server 2008 R2 Diagnostic Information Queries.sql -------------------------------------------------------------------------------- /Scripts/SQL Server 2012 Diagnostic Information Queries.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/Scripts/SQL Server 2012 Diagnostic Information Queries.sql -------------------------------------------------------------------------------- /Scripts/SQL Server 2014 Diagnostic Information Queries.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/Scripts/SQL Server 2014 Diagnostic Information Queries.sql -------------------------------------------------------------------------------- /Scripts/SQL Server 2016 Diagnostic Information Queries.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/Scripts/SQL Server 2016 Diagnostic Information Queries.sql -------------------------------------------------------------------------------- /Scripts/SQL Server 2017 Diagnostic Information Queries.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/Scripts/SQL Server 2017 Diagnostic Information Queries.sql -------------------------------------------------------------------------------- /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 alternative.sql: -------------------------------------------------------------------------------- 1 | -- source: http://www.brentozar.com/archive/2014/02/count-number-rows-table-sql-server/ 2 | DECLARE @TableName sysname 3 | SET @TableName = 'bigTransactionHistory' 4 | 5 | SELECT TBL.object_id, TBL.name, SUM(PART.rows) AS rows 6 | FROM sys.tables TBL 7 | INNER JOIN sys.partitions PART ON TBL.object_id = PART.object_id 8 | INNER JOIN sys.indexes IDX ON PART.object_id = IDX.object_id 9 | AND PART.index_id = IDX.index_id 10 | WHERE TBL.name = @TableName 11 | AND IDX.index_id < 2 12 | GROUP BY TBL.object_id, TBL.name; 13 | 14 | 15 | DECLARE @TableName sysname 16 | SET @TableName = 'bigTransactionHistory' 17 | 18 | SELECT OBJECT_NAME(object_id), SUM(row_count) AS rows 19 | FROM sys.dm_db_partition_stats 20 | WHERE object_id = OBJECT_ID(@TableName) 21 | AND index_id < 2 22 | GROUP BY OBJECT_NAME(object_id); -------------------------------------------------------------------------------- /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/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/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' else (Case when status = 2 then 'In Use' else 'Available' end) end as TextStatus, 23 | [Status] , 24 | REPLICATE('x', FileSize / MIN(FileSize) over()) as [BarChart ________________________________________________________________________________________________] 25 | FROM @logInfoResults; 26 | GO 27 | -------------------------------------------------------------------------------- /Scripts/Which_Filegroup_is_that_Partition_Using.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Source link: https://www.littlekendra.com/2017/01/31/which-filegroup-is-that-partition-using-how-many-rows-does-it-have/ 3 | Author: Kendra Little 4 | */ 5 | SELECT 6 | sc.name + N'.' + so.name as [Schema.Table], 7 | si.index_id as [Index ID], 8 | si.type_desc as [Structure], 9 | si.name as [Index], 10 | stat.row_count AS [Rows], 11 | stat.in_row_reserved_page_count * 8./1024./1024. as [In-Row GB], 12 | stat.lob_reserved_page_count * 8./1024./1024. as [LOB GB], 13 | p.partition_number AS [Partition #], 14 | pf.name as [Partition Function], 15 | CASE pf.boundary_value_on_right 16 | WHEN 1 then 'Right / Lower' 17 | ELSE 'Left / Upper' 18 | END as [Boundary Type], 19 | prv.value as [Boundary Point], 20 | fg.name as [Filegroup] 21 | FROM sys.partition_functions AS pf 22 | JOIN sys.partition_schemes as ps on ps.function_id=pf.function_id 23 | JOIN sys.indexes as si on si.data_space_id=ps.data_space_id 24 | JOIN sys.objects as so on si.object_id = so.object_id 25 | JOIN sys.schemas as sc on so.schema_id = sc.schema_id 26 | JOIN sys.partitions as p on 27 | si.object_id=p.object_id 28 | and si.index_id=p.index_id 29 | LEFT JOIN sys.partition_range_values as prv on prv.function_id=pf.function_id 30 | and p.partition_number= 31 | CASE pf.boundary_value_on_right WHEN 1 32 | THEN prv.boundary_id + 1 33 | ELSE prv.boundary_id 34 | END 35 | /* For left-based functions, partition_number = boundary_id, 36 | for right-based functions we need to add 1 */ 37 | JOIN sys.dm_db_partition_stats as stat on stat.object_id=p.object_id 38 | and stat.index_id=p.index_id 39 | and stat.index_id=p.index_id and stat.partition_id=p.partition_id 40 | and stat.partition_number=p.partition_number 41 | JOIN sys.allocation_units as au on au.container_id = p.hobt_id 42 | and au.type_desc ='IN_ROW_DATA' 43 | /* Avoiding double rows for columnstore indexes. */ 44 | /* We can pick up LOB page count from partition_stats */ 45 | JOIN sys.filegroups as fg on fg.data_space_id = au.data_space_id 46 | ORDER BY [Schema.Table], [Index ID], [Partition Function], [Partition #]; 47 | GO -------------------------------------------------------------------------------- /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/Which_sp_configure_Options_Clear_the_Plan_Cache.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Brent Ozar 3 | Source link: https://www.brentozar.com/archive/2017/09/sp_configure-options-clear-plan-cache/ 4 | */ 5 | 6 | DECLARE @string_to_execute NVARCHAR(1000), @current_name NVARCHAR(200), @current_value_in_use SQL_VARIANT, @current_maximum SQL_VARIANT; 7 | 8 | CREATE TABLE #configs (name NVARCHAR(200), value_in_use SQL_VARIANT, maximum SQL_VARIANT, clears_plan_cache BIT); 9 | INSERT INTO #configs (name, value_in_use, maximum, clears_plan_cache) 10 | SELECT name, value_in_use, maximum, 0 11 | FROM sys.configurations; 12 | 13 | DECLARE config_cursor CURSOR FOR 14 | SELECT name, value_in_use, maximum 15 | FROM #configs 16 | WHERE name NOT IN ('default language', 'default full-text language', 'min server memory (MB)', 'user options'); 17 | 18 | OPEN config_cursor; 19 | FETCH NEXT FROM config_cursor INTO @current_name, @current_value_in_use, @current_maximum; 20 | 21 | 22 | WHILE @@FETCH_STATUS = 0 23 | BEGIN 24 | /* Put something in the plan cache */ 25 | 26 | /* Run sp_configure to set it to maximum */ 27 | SET @string_to_execute = 'sp_configure ''' + @current_name + ''', ''' + CAST(@current_maximum AS NVARCHAR(100)) + '''; RECONFIGURE WITH OVERRIDE;'; 28 | EXEC(@string_to_execute); 29 | 30 | /* Check the plan cache */ 31 | IF NOT EXISTS(SELECT * FROM sys.dm_exec_query_stats) 32 | UPDATE #configs 33 | SET clears_plan_cache = 1 34 | WHERE name = @current_name; 35 | 36 | /* Run sp_configure to set it back */ 37 | SET @string_to_execute = 'sp_configure ''' + @current_name + ''', ''' + CAST(@current_value_in_use AS NVARCHAR(100)) + '''; RECONFIGURE WITH OVERRIDE;'; 38 | EXEC(@string_to_execute); 39 | 40 | FETCH NEXT FROM config_cursor INTO @current_name, @current_value_in_use, @current_maximum; 41 | END 42 | CLOSE config_cursor; 43 | DEALLOCATE config_cursor; 44 | 45 | SELECT name, clears_plan_cache 46 | FROM #configs 47 | WHERE clears_plan_cache = 1 48 | ORDER BY name; 49 | 50 | DROP TABLE #configs; 51 | -------------------------------------------------------------------------------- /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_database.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Jason Brimhall 3 | Original link: http://jasonbrimhall.info/2016/09/09/database-dropped/ 4 | */ 5 | 6 | DECLARE @DBName sysname = 'AdventureWorks2014' 7 | ,@d1 DATETIME 8 | ,@diff INT; 9 | 10 | SELECT ObjectName 11 | , ObjectID 12 | , DatabaseName 13 | , StartTime 14 | , EventClass 15 | , EventSubClass 16 | , ObjectType 17 | , ServerName 18 | , LoginName 19 | , NTUserName 20 | , ApplicationName 21 | , CASE EventClass 22 | WHEN 46 23 | THEN 'CREATE' 24 | WHEN 47 25 | THEN 'DROP' 26 | --WHEN 164 27 | -- THEN 'ALTER' 28 | END AS DDLOperation 29 | INTO #temp_trace 30 | FROM sys.fn_trace_gettable(CONVERT(VARCHAR(150), 31 | ( SELECT REVERSE(SUBSTRING(REVERSE(path), 32 | CHARINDEX('\',REVERSE(path)),256)) + 'log.trc' 33 | FROM sys.traces 34 | WHERE is_default = 1)), DEFAULT) T 35 | WHERE EventClass in (46,47) 36 | AND EventSubclass = 0 37 | AND ObjectType = 16964-- i just want database related events 38 | AND DatabaseName = ISNULL(@DBName,DatabaseName); 39 | 40 | 41 | SELECT @d1 = MIN(StartTime) 42 | FROM #temp_trace; 43 | 44 | SET @diff= DATEDIFF(hh,@d1,GETDATE()); 45 | 46 | 47 | SELECT @diff AS HrsSinceFirstChange 48 | , @d1 AS FirstChangeDate 49 | , sv.name AS obj_type_desc 50 | , tt.ObjectType 51 | , tt.DDLOperation 52 | , tt.DatabaseName,tt.ObjectName,tt.StartTime 53 | , tt.EventClass,tt.EventSubClass 54 | , tt.ServerName,tt.LoginName, tt.NTUserName 55 | , tt.ApplicationName 56 | , (dense_rank() OVER (ORDER BY ObjectName,ObjectType ) )%2 AS l1 57 | , (dense_rank() OVER (ORDER BY ObjectName,ObjectType,StartTime ))%2 AS l2 58 | FROM #temp_trace tt 59 | INNER JOIN sys.trace_events AS te 60 | ON tt.EventClass = te.trace_event_id 61 | INNER JOIN sys.trace_subclass_values tsv 62 | ON tt.EventClass = tsv.trace_event_id 63 | AND tt.ObjectType = tsv.subclass_value 64 | INNER JOIN master.dbo.spt_values sv 65 | ON tsv.subclass_value = sv.number 66 | AND sv.type = 'EOD' 67 | ORDER BY StartTime DESC; 68 | 69 | DROP TABLE #temp_trace; 70 | -------------------------------------------------------------------------------- /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/tempdb_Information.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Eric Russell 3 | Original link: http://www.sqlservercentral.com/scripts/tempdb/151252/ 4 | */ 5 | -- Query details about objects allocated in TEMPDB. This must be run in context of TEMPDB database. 6 | SET LOCK_TIMEOUT 10000; 7 | SET DEADLOCK_PRIORITY LOW; 8 | SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; 9 | 10 | USE tempdb; 11 | 12 | SELECT * FROM 13 | ( 14 | SELECT DISTINCT 15 | DB_NAME() AS DatabaseName 16 | , ps.object_id AS ObjectID 17 | , o.type_desc AS ObjectType 18 | , o.name AS ObjectName 19 | , o.create_date AS ObjectCreated 20 | , si.name AS IndexName 21 | , CASE si.index_id 22 | WHEN 0 THEN 'HEAP' 23 | WHEN 1 THEN 'CLUSTERED' 24 | ELSE 'NONCLUSTERED' 25 | END AS IndexType 26 | , ps.row_count AS RowsCount 27 | , ((ps.reserved_page_count * 8024) / 1024 / 1024) AS ReservedMB 28 | , trace.SPID 29 | , er.start_time AS RequestStartTime 30 | , trace.ApplicationName 31 | , OBJECT_NAME( qt.objectid, qt.dbid ) AS ProcedureName 32 | , SUBSTRING(CHAR(13) + SUBSTRING (qt.text,(er.statement_start_offset/2) + 1 33 | ,((CASE WHEN er.statement_end_offset = -1 34 | THEN LEN(CONVERT(NVARCHAR(MAX), qt.text)) * 2 35 | ELSE er.statement_end_offset 36 | END - er.statement_start_offset)/2) + 1) 37 | ,1,8000) AS StatementText 38 | , trace.HostName 39 | , trace.LoginName 40 | FROM sys.dm_db_partition_stats ps 41 | JOIN sys.tables AS o ON o.object_id = ps.OBJECT_ID AND o.is_ms_shipped = 0 42 | LEFT JOIN sys.indexes si ON si.object_id = o.object_id AND si.index_id = ps.index_id 43 | LEFT JOIN 44 | ( 45 | SELECT HostName, LoginName, SPID, ApplicationName, DatabaseName, ObjectID 46 | , ROW_NUMBER() OVER (PARTITION BY ObjectID ORDER BY StartTime DESC) MostRecentObjectReference 47 | FROM fn_trace_gettable( 48 | ( 49 | SELECT LEFT(path, LEN(path)-CHARINDEX('\', REVERSE(path))) + '\Log.trc' 50 | FROM sys.traces 51 | WHERE is_default = 1 52 | ), DEFAULT) 53 | WHERE ObjectID IS NOT NULL 54 | ) trace 55 | ON trace.ObjectID = ps.object_id 56 | AND trace.DatabaseName = 'tempdb' 57 | AND MostRecentObjectReference = 1 58 | LEFT JOIN sys.dm_exec_requests AS er 59 | ON er.session_id = trace.SPID 60 | OUTER APPLY sys.dm_exec_sql_text( er.sql_handle) AS qt 61 | ) AS T 62 | --WHERE ReservedMB > 0 63 | ORDER BY ReservedMB DESC; 64 | -------------------------------------------------------------------------------- /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/Ola_Maintenance_Solution/README.md: -------------------------------------------------------------------------------- 1 | # SQL Server Backup, Integrity Check, and Index and Statistics Maintenance 2 | 3 | Source link: [ola.hallengren.com](https://ola.hallengren.com) 4 | 5 | The SQL Server Maintenance Solution comprises scripts for running backups, integrity checks, and index and statistics maintenance 6 | on all editions of Microsoft SQL Server 2005, SQL Server 2008, SQL Server 2008 R2, SQL Server 2012, SQL Server 2014 and SQL Server 2016. 7 | The solution is based on stored procedures, the sqlcmd utility, and SQL Server Agent jobs. 8 | Ola Hallengren designed the solution for the most mission-critical environments, and it is used in many 9 | [organizations](https://ola.hallengren.com/organizations.html) around the world. 10 | Numerous SQL Server community experts recommend the SQL Server Maintenance Solution, which has been a Gold winner in the 11 | [2013](http://sqlmag.com/sql-server/best-free-sql-server-tool-2013), 12 | [2012](http://sqlmag.com/sql-server/2012-sql-server-pro-editors-best-and-community-choice-awards), 13 | [2011](http://sqlmag.com/sql-server/2011-sql-server-magazine-editors-best-and-community-choice-awards), 14 | and [2010](http://sqlmag.com/sql-server/2010-sql-server-magazine-editors-best-and-community-choice-awards) 15 | SQL Server Magazine Awards. 16 | The SQL Server Maintenance Solution is [free](https://ola.hallengren.com/license.html). 17 | 18 | 19 | ## Getting Started 20 | 21 | Download [MaintenanceSolution.sql](/Ola_Maintenance_Solution/MaintenanceSolution.sql). 22 | This script creates all the objects and jobs that you need. Learn more about using the SQL Server Maintenance Solution. 23 | 24 | You can also download the objects as separate scripts: 25 | - [DatabaseBackup](/Ola_Maintenance_Solution/DatabaseBackup.sql): SQL Server Backup 26 | - [DatabaseIntegrityCheck](/Ola_Maintenance_Solution/DatabaseIntegrityCheck.sql): SQL Server Integrity Check 27 | - [IndexOptimize](/Ola_Maintenance_Solution/IndexOptimize.sql): SQL Server Index and Statistics Maintenance 28 | - [CommandExecute](/Ola_Maintenance_Solution/CommandExecute.sql): Stored procedure to execute and log commands 29 | - [CommandLog](/Ola_Maintenance_Solution/CommandLog.sql): Table to log commands 30 | 31 | Note that you always need CommandExecute, DatabaseBackup, DatabaseIntegrityCheck, and IndexOptimize are using it. 32 | You need CommandLog if you are going to use the option to log commands to a table. 33 | -------------------------------------------------------------------------------- /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 | - [SQLQueryStress](/Solution/SQLQueryStress) (by Adam Machanic) 7 | - [SysJobHistory](/Solution/SysJobHistory) (by David Wentzel) 8 | -------------------------------------------------------------------------------- /Solution/SQLQueryStress/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | ## Contributing Issues 2 | 3 | ### Before Submitting an Issue 4 | First, please do a search in open issues to see if the issue or feature request has already been filed. If there is an issue add your comments to this issue. 5 | 6 | 7 | ## Writing Good Bug Reports and Feature Requests 8 | 9 | The more information you can provide, the more likely someone will be successful reproducing the issue and finding a fix. Whenever possible: 10 | 11 | * Provide reproducable steps, what the result of the steps was, an what you would have expected. 12 | * Screen shots of the issue/input/any error messages 13 | * Description of what you expect to happen 14 | * Animated GIFs 15 | * Code that demonstrates the issue 16 | 17 | ## Contributing Code 18 | 19 | The general development process is: 20 | 21 | 1. Fork this repo and clone it to your workstation. 22 | 2. Create a feature branch for your change. 23 | 3. Write code and tests. 24 | 4. Push your feature branch to github and open a pull request against master. 25 | -------------------------------------------------------------------------------- /Solution/SQLQueryStress/README.md: -------------------------------------------------------------------------------- 1 | # SqlQueryStress 2 | SQL query stress simulator created by Adam Machanic http://sqlblog.com/blogs/adam_machanic/archive/2016/01/04/sqlquerystress-the-source-code.aspx 3 | 4 | The goal of this tool was to enable the user to test a single query under some form of load -- up to 200 simultaneous threads. 5 | 6 | ## Contributing 7 | 8 | Any and all contributions are welcome! Please see the full [contributing guide](CONTRIBUTING.md) for more details. 9 | -------------------------------------------------------------------------------- /Solution/SQLQueryStress/src/SQLQueryStress.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 14 4 | VisualStudioVersion = 14.0.23107.0 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SQLQueryStress", "SQLQueryStress\SQLQueryStress.csproj", "{02A166A4-EE64-432F-AA6E-08C7984BD7BC}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {02A166A4-EE64-432F-AA6E-08C7984BD7BC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {02A166A4-EE64-432F-AA6E-08C7984BD7BC}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {02A166A4-EE64-432F-AA6E-08C7984BD7BC}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {02A166A4-EE64-432F-AA6E-08C7984BD7BC}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | EndGlobal 23 | -------------------------------------------------------------------------------- /Solution/SQLQueryStress/src/SQLQueryStress/App.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /Solution/SQLQueryStress/src/SQLQueryStress/BlockedBoundedBuffer.cs: -------------------------------------------------------------------------------- 1 | #region 2 | 3 | using System.Threading; 4 | 5 | #endregion 6 | 7 | namespace SQLQueryStress 8 | { 9 | public class BlockedBoundedBuffer 10 | { 11 | private readonly T[] _buffer; 12 | private int _count; 13 | 14 | private int _readNumber; 15 | private int _writeNumber; 16 | 17 | public BlockedBoundedBuffer(int bufferSize) 18 | { 19 | _buffer = new T[bufferSize]; 20 | _readNumber = -1; 21 | _writeNumber = -1; 22 | _count = 0; 23 | } 24 | 25 | public T Dequeue() 26 | { 27 | while (_count == 0) 28 | { 29 | lock (_buffer) 30 | { 31 | Monitor.Wait(_buffer); 32 | } 33 | } 34 | 35 | int read; 36 | 37 | do 38 | { 39 | read = Interlocked.Increment(ref _readNumber); 40 | 41 | if (read >= _buffer.Length) 42 | { 43 | lock (_buffer) 44 | { 45 | if (read >= _buffer.Length) 46 | { 47 | Interlocked.Exchange(ref _readNumber, 0); 48 | Interlocked.Exchange(ref _writeNumber, -1); 49 | Monitor.PulseAll(_buffer); 50 | } 51 | } 52 | } 53 | else 54 | break; 55 | } while (true); 56 | 57 | Interlocked.Decrement(ref _count); 58 | 59 | return _buffer[read]; 60 | } 61 | 62 | public void Enqueue(T input) 63 | { 64 | int write; 65 | 66 | do 67 | { 68 | write = Interlocked.Increment(ref _writeNumber); 69 | if (write >= _buffer.Length) 70 | { 71 | lock (_buffer) 72 | { 73 | Monitor.Wait(_buffer); 74 | } 75 | } 76 | else 77 | break; 78 | } while (true); 79 | 80 | _buffer[write] = input; 81 | 82 | if (Interlocked.Increment(ref _count) == 1) 83 | { 84 | lock (_buffer) 85 | { 86 | Monitor.PulseAll(_buffer); 87 | } 88 | } 89 | } 90 | } 91 | } -------------------------------------------------------------------------------- /Solution/SQLQueryStress/src/SQLQueryStress/DataViewer.cs: -------------------------------------------------------------------------------- 1 | #region 2 | 3 | using System; 4 | using System.Data; 5 | using System.Windows.Forms; 6 | 7 | #endregion 8 | 9 | namespace SQLQueryStress 10 | { 11 | public partial class DataViewer : Form 12 | { 13 | public DataViewer() 14 | { 15 | InitializeComponent(); 16 | } 17 | 18 | public DataTable DataView { get; set; } 19 | 20 | private void Form2_Load(object sender, EventArgs e) 21 | { 22 | dataGridView1.DataSource = DataView; 23 | 24 | var columnWidth = (dataGridView1.Width - 41) / DataView.Columns.Count; 25 | 26 | foreach (DataGridViewColumn col in dataGridView1.Columns) 27 | col.Width = columnWidth; 28 | } 29 | 30 | public void Repaint() 31 | { 32 | dataGridView1.Invalidate(); 33 | } 34 | } 35 | } -------------------------------------------------------------------------------- /Solution/SQLQueryStress/src/SQLQueryStress/Options.cs: -------------------------------------------------------------------------------- 1 | #region 2 | 3 | using System; 4 | using System.Windows.Forms; 5 | 6 | #endregion 7 | 8 | namespace SQLQueryStress 9 | { 10 | public partial class Options : Form 11 | { 12 | private readonly Form1.QueryStressSettings _settings; 13 | 14 | public Options(Form1.QueryStressSettings settings) 15 | { 16 | _settings = settings; 17 | 18 | InitializeComponent(); 19 | 20 | connectionTimeout_numericUpDown.Value = settings.ConnectionTimeout; 21 | commandTimeout_numericUpDown.Value = settings.CommandTimeout; 22 | connectionPooling_checkBox.Checked = settings.EnableConnectionPooling; 23 | IOStatistics_checkBox.Checked = settings.CollectIoStats; 24 | timeStatistics_checkBox.Checked = settings.CollectTimeStats; 25 | clientDataRetrieval_checkBox.Checked = settings.ForceDataRetrieval; 26 | } 27 | 28 | private void cancel_button_Click(object sender, EventArgs e) 29 | { 30 | Dispose(); 31 | } 32 | 33 | private void ok_button_Click(object sender, EventArgs e) 34 | { 35 | _settings.ConnectionTimeout = (int) connectionTimeout_numericUpDown.Value; 36 | _settings.CommandTimeout = (int) commandTimeout_numericUpDown.Value; 37 | _settings.EnableConnectionPooling = connectionPooling_checkBox.Checked; 38 | _settings.CollectIoStats = IOStatistics_checkBox.Checked; 39 | _settings.CollectTimeStats = timeStatistics_checkBox.Checked; 40 | _settings.ForceDataRetrieval = clientDataRetrieval_checkBox.Checked; 41 | 42 | Dispose(); 43 | } 44 | } 45 | } -------------------------------------------------------------------------------- /Solution/SQLQueryStress/src/SQLQueryStress/Program.cs: -------------------------------------------------------------------------------- 1 | #region 2 | 3 | using System; 4 | using System.Windows.Forms; 5 | 6 | #endregion 7 | 8 | namespace SQLQueryStress 9 | { 10 | internal static class Program 11 | { 12 | /// 13 | /// The main entry point for the application. 14 | /// 15 | [STAThread] 16 | private static void Main(string[] args) 17 | { 18 | Application.EnableVisualStyles(); 19 | Application.SetCompatibleTextRenderingDefault(false); 20 | 21 | Form1 f = args.Length > 0 ? new Form1(args[0]) : new Form1(); 22 | 23 | f.StartPosition = FormStartPosition.CenterScreen; 24 | Application.Run(f); 25 | } 26 | } 27 | } -------------------------------------------------------------------------------- /Solution/SQLQueryStress/src/SQLQueryStress/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | #region 2 | 3 | using System.Reflection; 4 | using System.Runtime.InteropServices; 5 | 6 | #endregion 7 | 8 | // General Information about an assembly is controlled through the following 9 | // set of attributes. Change these attribute values to modify the information 10 | // associated with an assembly. 11 | 12 | [assembly: AssemblyTitle("SQLQueryStress")] 13 | [assembly: AssemblyDescription("SQL Server Load Test Tool")] 14 | [assembly: AssemblyConfiguration("")] 15 | [assembly: AssemblyCompany("amachanic@gmail.com")] 16 | [assembly: AssemblyProduct("SQLQueryStress")] 17 | [assembly: AssemblyCopyright("Copyright © 2006, 2007 Adam Machanic")] 18 | [assembly: AssemblyTrademark("")] 19 | [assembly: AssemblyCulture("")] 20 | 21 | // Setting ComVisible to false makes the types in this assembly not visible 22 | // to COM components. If you need to access a type in this assembly from 23 | // COM, set the ComVisible attribute to true on that type. 24 | 25 | [assembly: ComVisible(false)] 26 | 27 | // The following GUID is for the ID of the typelib if this project is exposed to COM 28 | 29 | [assembly: Guid("e4c26a22-8376-4ff3-aa7f-878ebd9f34b3")] 30 | 31 | // Version information for an assembly consists of the following four values: 32 | // 33 | // Major Version 34 | // Minor Version 35 | // Build Number 36 | // Revision 37 | // 38 | 39 | [assembly: AssemblyVersion("0.9.7.0")] 40 | [assembly: AssemblyFileVersion("0.9.7.0")] -------------------------------------------------------------------------------- /Solution/SQLQueryStress/src/SQLQueryStress/Properties/Settings.Designer.cs: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This code was generated by a tool. 4 | // Runtime Version:4.0.30319.42000 5 | // 6 | // Changes to this file may cause incorrect behavior and will be lost if 7 | // the code is regenerated. 8 | // 9 | //------------------------------------------------------------------------------ 10 | 11 | namespace SQLQueryStress.Properties { 12 | 13 | 14 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] 15 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "14.0.0.0")] 16 | internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { 17 | 18 | private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); 19 | 20 | public static Settings Default { 21 | get { 22 | return defaultInstance; 23 | } 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Solution/SQLQueryStress/src/SQLQueryStress/Properties/Settings.settings: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Solution/SQLQueryStress/src/SQLQueryStress/Properties/app.manifest: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /Solution/SQLQueryStress/src/SQLQueryStress/Resources/QueryStressIcon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/Solution/SQLQueryStress/src/SQLQueryStress/Resources/QueryStressIcon.ico -------------------------------------------------------------------------------- /Solution/SQLQueryStress/src/SQLQueryStress/SQLQueryStress_Documentation.doc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/Solution/SQLQueryStress/src/SQLQueryStress/SQLQueryStress_Documentation.doc -------------------------------------------------------------------------------- /Solution/SQLQueryStress/src/SQLQueryStress/sqlQueryStress.snk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/Solution/SQLQueryStress/src/SQLQueryStress/sqlQueryStress.snk -------------------------------------------------------------------------------- /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/sp_ChangeDatabaseOwnerShip.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Original link: https://sqlundercover.com/2017/08/18/undercover-toolbox-sp_changedatabaseownership-producing-statements-to-alter-authorisation/ 3 | */ 4 | 5 | USE [master] 6 | go 7 | 8 | /********************************************** 9 | --Procedure Name: sp_ChangeDatabaseOwnerShip 10 | --Author: Adrian Buckman 11 | --Create Date: 17/08/2017 12 | 13 | --Description: Produce a script that will provide ALTER statements to change the database 14 | --ownership to the new owner and also ALTER statements to revert back to the old owner 15 | 16 | --Revision History: 17 | . 18 | 19 | **********************************************/ 20 | 21 | CREATE PROCEDURE sp_ChangeDatabaseOwnerShip 22 | ( 23 | @DBOwner NVARCHAR(128) = NULL, 24 | @Help BIT = 0 25 | ) 26 | AS 27 | 28 | IF @Help = 1 29 | BEGIN 30 | PRINT 'Parameters: 31 | @DBOwner NVARCHAR(128) - Set the new owner name here' 32 | END 33 | 34 | IF @Help = 0 35 | BEGIN 36 | DECLARE @UserSid VARBINARY = SUSER_SID(@DBOwner) 37 | 38 | IF @UserSid IS NOT NULL 39 | BEGIN 40 | 41 | SELECT DISTINCT 42 | sys.databases.Name AS Databasename, 43 | COALESCE(SUSER_SNAME(sys.databases.owner_sid),'') AS CurrentOwner, 44 | 'ALTER AUTHORIZATION ON DATABASE::['+sys.databases.name +'] TO ['+@DBOwner+'];' AS ChangeToNewOwner, 45 | 'ALTER AUTHORIZATION ON DATABASE::['+sys.databases.name +'] TO ['+COALESCE(SUSER_SNAME(sys.databases.owner_sid),'')+'];' AS RevertToOriginalOwner 46 | FROM 47 | sys.databases 48 | LEFT JOIN sys.availability_databases_cluster ADC ON sys.databases.name = ADC.database_name 49 | LEFT JOIN sys.dm_hadr_availability_group_states st ON st.group_id = ADC.group_id 50 | LEFT JOIN master.sys.availability_groups ag ON st.group_id = AG.group_id 51 | WHERE (primary_replica = @@Servername 52 | AND sys.databases.owner_sid != @UserSid) 53 | OR (sys.databases.owner_sid != @UserSid 54 | AND sys.databases.state = 0 55 | AND sys.databases.source_database_id IS NULL 56 | AND sys.databases.replica_id IS NULL) 57 | 58 | END 59 | ELSE 60 | BEGIN 61 | RAISERROR('No SID found for the owner name you have provided - please check the owner name and try again',11,1) 62 | END 63 | 64 | END -------------------------------------------------------------------------------- /Stored_Procedure/sp_Defrag_Indexes.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/Stored_Procedure/sp_Defrag_Indexes.sql -------------------------------------------------------------------------------- /Stored_Procedure/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/sp_FailedJobs.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Original link: https://sqlundercover.com/2017/06/16/undercover-toolbox-sp_failedjobs-the-quick-way-to-check-for-failed-agent-jobs 3 | */ 4 | 5 | USE [master] 6 | GO 7 | 8 | /************************************************ 9 | Author: Adrian Buckman 10 | Date: 16/06/2017 11 | SQLUnderCover.com 12 | ************************************************/ 13 | 14 | CREATE PROCEDURE sp_FailedJobs 15 | ( 16 | @FromDate DATETIME = NULL, 17 | @ToDate DATETIME = NULL 18 | ) 19 | AS 20 | BEGIN 21 | 22 | IF @FromDate IS NULL BEGIN SET @FromDate = DATEADD(Minute,-720,GETDATE()) END 23 | IF @ToDate IS NULL BEGIN SET @ToDate = GETDATE() END 24 | 25 | SELECT 26 | Jobs.name, 27 | JobHistory.step_id, 28 | JobHistory.FailedRunDate, 29 | CAST(JobHistory.LastError AS VARCHAR(250)) AS LastError 30 | FROM msdb.dbo.sysjobs Jobs 31 | CROSS APPLY (Select TOP 1 JobHistory.step_id,JobHistory.run_date, 32 | CASE JobHistory.run_date WHEN 0 THEN NULL ELSE 33 | convert(datetime, 34 | stuff(stuff(cast(JobHistory.run_date as nchar(8)), 7, 0, '-'), 5, 0, '-') + N' ' + 35 | stuff(stuff(substring(cast(1000000 + JobHistory.run_time as nchar(7)), 2, 6), 5, 0, ':'), 3, 0, ':'), 36 | 120) END AS [FailedRunDate] ,[Message] AS LastError 37 | FROM msdb.dbo.sysjobhistory JobHistory 38 | WHERE 39 | Run_status = 0 40 | and Jobs.job_id = JobHistory.job_id 41 | ORDER BY 42 | [FailedRunDate] DESC,step_id DESC) JobHistory 43 | 44 | WHERE Jobs.enabled = 1 45 | AND JobHistory.FailedRunDate >= @FromDate AND JobHistory.FailedRunDate <= @ToDate 46 | AND NOT EXISTS (SELECT [LastSuccessfulrunDate] 47 | FROM( 48 | SELECT CASE JobHistory.run_date WHEN 0 THEN NULL ELSE 49 | convert(datetime, 50 | stuff(stuff(cast(JobHistory.run_date as nchar(8)), 7, 0, '-'), 5, 0, '-') + N' ' + 51 | stuff(stuff(substring(cast(1000000 + JobHistory.run_time as nchar(7)), 2, 6), 5, 0, ':'), 3, 0, ':'), 52 | 120) END AS [LastSuccessfulrunDate] 53 | FROM msdb.dbo.sysjobhistory JobHistory 54 | WHERE 55 | Run_status = 1 56 | AND Jobs.job_id = JobHistory.job_id 57 | ) JobHistory2 58 | WHERE JobHistory2.[LastSuccessfulrunDate] > JobHistory.[FailedRunDate]) 59 | AND NOT EXISTS (SELECT Session_id 60 | From msdb.dbo.sysjobactivity JobActivity 61 | where Jobs.job_id = JobActivity.job_id 62 | AND stop_execution_date is null 63 | AND SESSION_id = (Select MAX(Session_ID) From msdb.dbo.sysjobactivity JobActivity 64 | where Jobs.job_id = JobActivity.job_id) 65 | ) 66 | AND Jobs.Name != 'syspolicy_purge_history' 67 | 68 | ORDER BY name 69 | 70 | END 71 | -------------------------------------------------------------------------------- /Stored_Procedure/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/sp_IndexAnalysis-v11.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/Stored_Procedure/sp_IndexAnalysis-v11.sql -------------------------------------------------------------------------------- /Stored_Procedure/sp_generate_merge.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/Stored_Procedure/sp_generate_merge.sql -------------------------------------------------------------------------------- /Stored_Procedure/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/usp_MonitorIdentityColumn.sql: -------------------------------------------------------------------------------- 1 | IF OBJECT_ID('dbo.usp_MonitorIdentityColumn', 'P') IS NULL 2 | EXECUTE('CREATE PROCEDURE dbo.usp_MonitorIdentityColumn as SELECT 1'); 3 | GO 4 | 5 | 6 | ALTER PROCEDURE dbo.usp_MonitorIdentityColumn ( 7 | @databaseName SYSNAME 8 | , @schemaMask SYSNAME = NULL 9 | , @tableMask SYSNAME = NULL 10 | , @debug BIT = 0 11 | ) 12 | AS 13 | /* 14 | EXECUTE dbo.usp_MonitorIdentityColumn 15 | @databaseName = 'YourDatabase' 16 | , @schemaMask = '%YourMask%' 17 | , @tableMask = '%YourMask%' 18 | */ 19 | SET NOCOUNT ON; 20 | 21 | BEGIN TRY 22 | DECLARE @tsqlCommand NVARCHAR(MAX) = N''; 23 | DECLARE @ParamDefinitionIndentity NVARCHAR(500) = N'@DabataseNameIN SYSNAME'; 24 | 25 | SET @tsqlCommand = N' 26 | USE ' + @databaseName + '; 27 | 28 | DECLARE @DataTypeValue AS TABLE (DataType VARCHAR(50), MinValue BIGINT, MaxValue BIGINT); 29 | 30 | INSERT INTO @DataTypeValue VALUES 31 | (''tinyint'', 0, 255), 32 | (''smallint'', -32768, 32767), 33 | (''int'', -2147483648, 2147483647), 34 | (''bigint'', -9223372036854775808, 9223372036854775807); 35 | 36 | SELECT DISTINCT SS.name AS SchemaName 37 | , TN.name AS TableName 38 | , IC.name AS ColumnName 39 | , TYPE_NAME(IC.system_type_id) AS ColumnDataType 40 | , DTM.MinValue AS MinDataTypeValue 41 | , DTM.MaxValue AS MaxDataTypeValue 42 | , IC.seed_value IdentitySeed 43 | , IC.increment_value AS IdentityIncrement 44 | , IC.last_value AS LastIdentityValue 45 | , DBPS.row_count AS NumberOfRows 46 | , (CONVERT(decimal(9,7), CONVERT(bigint,IC.last_value) * 100 / DTM.MaxValue)) AS ReachMaxValuePercent 47 | FROM sys.identity_columns IC 48 | INNER JOIN sys.tables TN ON IC.object_id = TN.object_id 49 | INNER JOIN sys.schemas SS ON TN.schema_id = SS.schema_id 50 | INNER JOIN @DataTypeValue DTM ON TYPE_NAME(IC.system_type_id)=DTM.DataType 51 | INNER JOIN sys.dm_db_partition_stats DBPS ON DBPS.object_id =IC.object_id 52 | INNER JOIN sys.indexes as IDX ON DBPS.index_id =IDX.index_id 53 | WHERE DBPS.row_count > 0 AND TN.name LIKE ''' + ISNULL(@tableMask, '%') + ''' 54 | AND SS.name LIKE ''' + ISNULL(@schemaMask, '%') + ''' 55 | ORDER BY ReachMaxValuePercent DESC; 56 | '; 57 | 58 | IF @debug = 1 PRINT @tsqlCommand 59 | ELSE 60 | EXECUTE sp_executesql @tsqlCommand; 61 | 62 | END TRY 63 | 64 | BEGIN CATCH 65 | EXECUTE dbo.usp_LogError; 66 | EXECUTE dbo.usp_PrintError; 67 | END CATCH; 68 | GO 69 | -------------------------------------------------------------------------------- /Stored_Procedure/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/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/usp_PrintString.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/Stored_Procedure/usp_PrintString.sql -------------------------------------------------------------------------------- /Stored_Procedure/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/usp_SearchOnAllDB.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/Stored_Procedure/usp_SearchOnAllDB.sql -------------------------------------------------------------------------------- /Stored_Procedure/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/RemoveNonAlphaCharacters.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/User_Defined_Function/RemoveNonAlphaCharacters.sql -------------------------------------------------------------------------------- /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_CalculateDistanceBetween2Coordinates.sql: -------------------------------------------------------------------------------- 1 | IF OBJECT_ID('dbo.udf_CalculateDistanceBetween2Coordinates', 'FN') IS NULL 2 | EXECUTE ('CREATE FUNCTION dbo.udf_CalculateDistanceBetween2Coordinates() RETURNS INT AS BEGIN RETURN 1 END;'); 3 | GO 4 | 5 | CREATE FUNCTION dbo.udf_CalculateDistanceBetween2Coordinates 6 | ( 7 | @Lat1 Float(18), 8 | @Long1 Float(18), 9 | @Lat2 Float(18), 10 | @Long2 Float(18), 11 | @ReturnType VarChar(10) 12 | ) 13 | 14 | Returns Float(18) 15 | 16 | AS 17 | /* 18 | Note 19 | Author: Vignesh Arulmani 20 | Original link: http://www.sqlservercentral.com/scripts/Calculate+Distance/118083/ 21 | Examples 22 | select dbo.udf_CalculateDistanceBetween2Coordinates('37.7749300 ','-122.4194200','34.0522222','-118.2427778','Miles'); 23 | select dbo.udf_CalculateDistanceBetween2Coordinates('37.7749300 ','-122.4194200','34.0522222','-118.2427778','Kilometers'); 24 | select dbo.udf_CalculateDistanceBetween2Coordinates('37.7749300 ','-122.4194200','34.0522222','-118.2427778','Meters'); 25 | select dbo.udf_CalculateDistanceBetween2Coordinates('37.7749300 ','-122.4194200','34.0522222','-118.2427778','Feet'); 26 | */ 27 | Begin 28 | 29 | Declare @R Float(8); 30 | Declare @dLat Float(18); 31 | Declare @dLon Float(18); 32 | Declare @a Float(18); 33 | Declare @c Float(18); 34 | Declare @d Float(18); 35 | 36 | Set @R = 37 | Case @ReturnType 38 | When 'Miles' Then 3956.55 39 | When 'Kilometers' Then 6367.45 40 | When 'Feet' Then 20890584 41 | When 'Meters' Then 6367450 42 | Else 20890584 43 | End 44 | 45 | Set @dLat = Radians(@lat2 - @lat1); 46 | 47 | Set @dLon = Radians(@long2 - @long1); 48 | 49 | Set @a = Sin(@dLat / 2) 50 | * Sin(@dLat / 2) 51 | + Cos(Radians(@lat1)) 52 | * Cos(Radians(@lat2)) 53 | * Sin(@dLon / 2) 54 | * Sin(@dLon / 2); 55 | Set @c = 2 * Atn2(sqrt(@a),sqrt(1-@a)); 56 | 57 | Set @d = @R * @c; 58 | Return @d; 59 | 60 | End; 61 | Go 62 | -------------------------------------------------------------------------------- /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_Is16digitValidCard.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Original link: https://www.simple-talk.com/blogs/2016/02/16/the-luhn-algorithm-in-sql/ 3 | Author: Phil Factor 4 | */ 5 | IF OBJECT_ID(N'dbo.udf_Is16digitValidCard', N'FN') IS NULL 6 | EXECUTE('CREATE FUNCTION dbo.udf_Is16digitValidCard() RETURNS INT AS BEGIN RETURN 1 END;'); 7 | GO 8 | 9 | 10 | ALTER FUNCTION dbo.udf_Is16digitValidCard( 11 | @Card CHAR(16) 12 | ) 13 | RETURNS TINYINT 14 | AS 15 | /* 16 | SELECT dbo.udf_Is16digitValidCard('5019710710103742') 17 | */ 18 | BEGIN 19 | RETURN CASE 20 | WHEN @Card LIKE '%[^0-9]%' THEN 0 21 | WHEN @Card IS NULL THEN 0 22 | WHEN ( 23 | + 2 * CAST(SUBSTRING(@Card, 1, 1) AS TINYINT) / 10 24 | + 2 * CAST(SUBSTRING(@Card, 1, 1) AS TINYINT) % 10 25 | + CAST(SUBSTRING(@Card, 2, 1) AS TINYINT) 26 | + 2 * CAST(SUBSTRING(@Card, 3, 1) AS TINYINT) / 10 27 | + 2 * CAST(SUBSTRING(@Card, 3, 1) AS TINYINT) % 10 28 | + CAST(SUBSTRING(@Card, 4, 1) AS TINYINT) 29 | + 2 * CAST(SUBSTRING(@Card, 5, 1) AS TINYINT) / 10 30 | + 2 * CAST(SUBSTRING(@Card, 5, 1) AS TINYINT) % 10 31 | + CAST(SUBSTRING(@Card, 6, 1) AS TINYINT) 32 | + 2 * CAST(SUBSTRING(@Card, 7, 1) AS TINYINT) / 10 33 | + 2 * CAST(SUBSTRING(@Card, 7, 1) AS TINYINT) % 10 34 | + CAST(SUBSTRING(@Card, 8, 1) AS TINYINT) 35 | + 2 * CAST(SUBSTRING(@Card, 9, 1) AS TINYINT) / 10 36 | + 2 * CAST(SUBSTRING(@Card, 9, 1) AS TINYINT) % 10 37 | + CAST(SUBSTRING(@Card, 10, 1) AS TINYINT) 38 | + 2 * CAST(SUBSTRING(@Card, 11, 1) AS TINYINT) / 10 39 | + 2 * CAST(SUBSTRING(@Card, 11, 1) AS TINYINT) % 10 40 | + CAST(SUBSTRING(@Card, 12, 1) AS TINYINT) 41 | + 2 * CAST(SUBSTRING(@Card, 13, 1) AS TINYINT) / 10 42 | + 2 * CAST(SUBSTRING(@Card, 13, 1) AS TINYINT) % 10 43 | + CAST(SUBSTRING(@Card, 14, 1) AS TINYINT) 44 | + 2 * CAST(SUBSTRING(@Card, 15, 1) AS TINYINT) / 10 45 | + 2 * CAST(SUBSTRING(@Card, 15, 1) AS TINYINT) % 10 46 | + CAST(SUBSTRING(@Card, 16, 1) AS TINYINT) 47 | ) % 10 = 0 THEN 1 48 | ELSE 0 49 | END; 50 | END; 51 | GO 52 | -------------------------------------------------------------------------------- /User_Defined_Function/udf_IsValidCard.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/User_Defined_Function/udf_IsValidCard.sql -------------------------------------------------------------------------------- /User_Defined_Function/udf_PatternSplitLoop.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SQL-Server-projects/sqlserver-kit/462c209a18450945b64fe8fb7a3229917717b83a/User_Defined_Function/udf_PatternSplitLoop.sql -------------------------------------------------------------------------------- /User_Defined_Function/udf_QueriesWithParameterizationProblems.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Author: Dennes Torres 3 | Original link: https://www.red-gate.com/simple-talk/sql/database-administration/query-store-parameterization-problems 4 | Description: Query Store and Parameterization Problems 5 | */ 6 | 7 | 8 | CREATE FUNCTION dbo.QueriesWithParameterizationProblems() 9 | RETURNS TABLE 10 | AS 11 | RETURN 12 | ( 13 | -- Parameterized queries with text and most recent planId 14 | -- related with runtime stats grouped 15 | -- Filtering system queries 16 | select qsq.query_id, 17 | max(qsqt.query_sql_text) query_sql_text, 18 | max(qsp.plan_id) plan_id, 19 | max(qsrs.max_duration) max_duration, 20 | max(qsrs.max_cpu_time) max_cpu_time, 21 | min(qsrs.min_cpu_time) min_cpu_time, 22 | min(qsrs.min_duration) min_duration, 23 | max(qsrs.stdev_duration) stdev_duration, 24 | max(qsrs.stdev_cpu_time) stdev_cpu_time 25 | from sys.query_store_query qsq, 26 | sys.query_store_query_text qsqt, 27 | sys.query_store_plan qsp, 28 | sys.query_store_runtime_stats qsrs 29 | where qsq.query_text_id= qsqt.query_text_id 30 | and qsp.query_id=qsq.query_id 31 | and qsrs.plan_id=qsp.plan_id 32 | and (qsq.query_parameterization_type<>0 33 | or qsqt.query_sql_text like '%@%') 34 | and qsq.is_internal_query=0 35 | and qsqt.query_sql_text not like '%sys.%' 36 | and qsqt.query_sql_text not like '%sys[ ].%' 37 | and qsqt.query_sql_text not like '%@[sys@].%' escape '@' 38 | and qsqt.query_sql_text not like '%INFORMATION_SCHEMA%' 39 | and qsqt.query_sql_text not like '%msdb%' 40 | and qsqt.query_sql_text not like '%master%' 41 | and qsp.last_execution_time=(select max(last_execution_time) 42 | from sys.query_store_plan qsp2 43 | where qsp2.query_id= qsp.query_id) 44 | group by qsq.query_id 45 | ) 46 | GO 47 | -------------------------------------------------------------------------------- /User_Defined_Function/udf_RenderXMLToString.sql: -------------------------------------------------------------------------------- 1 | -- ============================================= 2 | -- Author: Andrei Solntsev 3 | -- Create date: Feb 2013 4 | -- Description: Converts xml value to nvarchar with formatting 5 | -- ============================================= 6 | ALTER FUNCTION dbo.udf_RenderXMLToString 7 | ( 8 | @xml xml 9 | ) 10 | RETURNS nvarchar(max) 11 | AS 12 | BEGIN 13 | DECLARE @ret nvarchar(max) = ''; -- return value 14 | DECLARE @s nvarchar(max); -- string to render 15 | DECLARE @ss nvarchar(max); -- single line of text from @s 16 | DECLARE @NewLine nvarchar(max) = ' 17 | '; 18 | 19 | DECLARE @Level int = 0, @LineBegins int = 1, @LineEnds int = 0; 20 | 21 | SET @s = CONVERT(nvarchar(max), @xml, 1); 22 | 23 | IF LEN(@s) > 2 24 | BEGIN 25 | SET @s = REPLACE(REPLACE(@s, '<', '|<'),'|| 0 33 | BEGIN 34 | SET @ss = SUBSTRING(@s, @LineBegins, @LineEnds-@LineBegins); 35 | 36 | IF @ss LIKE '<_%>%<[/]_%>' OR @ss LIKE '<_%[/]>' -- one line tag on the same level 37 | SET @ret = @ret + REPLICATE(' ', @Level) + @ss + @NewLine 38 | ELSE IF @ss LIKE '<[/]_%>' -- ending tag only 39 | BEGIN 40 | SET @Level = @Level - 1; 41 | SET @ret = @ret + REPLICATE(' ', @Level) + @ss + @NewLine; 42 | END 43 | ELSE IF @ss LIKE '<[^/]%[^/]>' -- starting tag only 44 | BEGIN 45 | SET @ret = @ret + REPLICATE(' ', @Level) + @ss + @NewLine; 46 | SET @Level = @Level + 1; 47 | END 48 | ELSE SET @ret = @ret + @ss + @NewLine; -- any text string without tags 49 | 50 | SET @LineBegins = @LineEnds+1; 51 | END ELSE BREAK; 52 | END 53 | SET @ret = LEFT(@ret, LEN(@ret)-2); -- Remove last CRLF 54 | END 55 | RETURN @ret 56 | END 57 | GO 58 | -------------------------------------------------------------------------------- /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_StringComparisonsLevenshteinFull-matrix.sql: -------------------------------------------------------------------------------- 1 | 2 | alter FUNCTION LevenschteinDifference 3 | ( 4 | @FirstString nVarchar(255), @SecondString nVarchar(255) 5 | ) 6 | RETURNS int 7 | as begin 8 | Declare @PseudoMatrix table 9 | (location int identity primary key, 10 | firstorder int not null, 11 | Firstch nchar(1), 12 | secondorder int not null, 13 | Secondch nchar(1), 14 | Thevalue int not null default 0, 15 | PreviousRowValues varchar(200) 16 | ) 17 | 18 | insert into @PseudoMatrix (firstorder, firstch, secondorder, secondch, TheValue ) 19 | SELECT TheFirst.number,TheFirst.ch, TheSecond.number,TheSecond.ch,0 20 | FROM --divide up the first string into a table of characters/sequence 21 | (SELECT number, SUBSTRING(@FirstString,number,1) AS ch 22 | FROM numbers WHERE number <= LEN(@FirstString) union all Select 0,Char(0)) TheFirst 23 | cross JOIN --divide up the second string into a table of characters/sequence 24 | (SELECT number, SUBSTRING(@SecondString,number,1) AS ch 25 | FROM numbers WHERE number <= LEN(@SecondString) union all Select 0,Char(0)) TheSecond 26 | --ON Thefirst.ch= Thesecond.ch --do all valid matches 27 | order by TheFirst.number, TheSecond.number 28 | 29 | Declare @current Varchar(255) 30 | Declare @previous Varchar(255) 31 | Declare @TheValue int 32 | Declare @Deletion int, @Insertion int, @Substitution int, @minim int 33 | Select @current='', @previous='' 34 | Update @PseudoMatrix 35 | Set 36 | @Deletion=@TheValue+1, 37 | @Insertion=ascii(substring(@previous,secondorder+1,1))+1, 38 | @Substitution=ascii(substring(@previous,(secondorder),1)) +1, 39 | @minim=case when @Deletion<@Insertion then @Deletion else @insertion end, 40 | @TheValue = Thevalue = case --when Firstorder+SecondOrder=0 then 0 41 | when SecondOrder=0 then FirstOrder 42 | When FirstOrder=0 then Secondorder 43 | when FirstCh=SecondCh then ascii(substring(@previous,(secondorder),1)) 44 | else case when @Minim<@Substitution then @Minim else @Substitution end 45 | end, 46 | @Previous=PreviousRowValues=case when secondorder =0 then @current else @Previous end, 47 | @current= case when secondorder =0 then char(@TheValue) else @Current+char(@TheValue) end 48 | return @TheValue 49 | End 50 | Go -------------------------------------------------------------------------------- /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 | ; --------------------------------------------------------------------------------