├── Scripts
├── README.md
├── Database_Mail_Problems.sql
├── Trace_Flag
│ ├── Trace_Flag_460.sql
│ ├── Trace_Flag_8726.sql
│ └── Trace_Flag_8727.sql
├── Monitor_Deadlocks_with_Extended_Events.sql
├── SQL Server 2005 Diagnostic Information Queries.sql
├── SQL Server 2008 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 2019 Diagnostic Information Queries.sql
├── SQL Server 2008 R2 Diagnostic Information Queries.sql
├── Truncate log file.sql
├── How_much_will_it_cost_or_save_to_rebuild_that_index.sql
├── SQL Managed Instance Diagnostic Information Queries.sql
├── SQL Server 2016 SP1 Diagnostic Information Queries.sql
├── SQL Server 2016 SP2 Diagnostic Information Queries.sql
├── Run_scripts.bat
├── Windows logins not in AD.sql
├── Enable Microsoft.ACE.OLEDB.12.0.sql
├── Get_SQLServer_Startup_Parameters.sql
├── Get_SQL_Server_Backup_Directory.sql
├── Count character matches.sql
├── PIVOT_Columns_generator.sql
├── Remove_Leading_and_Trailing_Backward_and_Forward_Slashes.sql
├── SQL_Server_Fixed_Role_Permissions.sql
├── Line_Of_Codes_In_database.sql
├── Queries_vulnerable_to_SQL_injection.sql
├── DynamicallyGenerateDMAStatement.sql
├── Get_SQL_Server_Agent_Information.sql
├── Listing_SQL_Agent_Jobs_Running_at_a_Specific_Time.sql
├── How_to_obtain_the_deadlocks_on_Azure.sql
├── Extract_Scale_Part_From_Decimal_Number.sql
├── Identifying_In-Memory_Objects_When_Querying_the_Transaction_Log.sql
├── Visualizing_VLF.sql
├── glen_berry_diagnostic_queries_links.txt
├── Table_Count_Fast_Alternatives.sql
├── When_SQL_Server_Was_Installed.sql
├── Fast_alternative_to_sp_WhoIsActive.sql
├── Get_Database_Size_With_Graph.sql
├── Estimate_When_Long_Running_SQL_Processes_Will_Finish.sql
├── GenerateTSQLTimeSlices.sql
├── Dynamic_GRANT_Generation.sql
├── Restore_Database_Dynamic_SQL.sql
├── LatchStats.sql
├── Create_2_Million_Tables.sql
├── PowerSavingCheck.sql
├── CPU_Utilization.sql
├── Generate_table_definition_to_match_query.sql
├── Tempdb_Contention.sql
├── Suspect_Database_Pages.sql
├── Count_Database_Reads_and_Writes.sql
├── Reseed_Identity_Column_Value_To_Last_Value.sql
├── Using_OPENROWSET_to_Query_Excel.sql
├── Get_Amazon_RDS_Instance_Size.sql
├── Objects_Size_In_Database.sql
├── Compare_2_tables_by_column_names.sql
├── Bad_Query_Example_13_JOINS.sql
├── Get_Statistics_Details.sql
├── SQL_Azure_Approximate_Datetime_Restart.sql
├── Job_AG_Failover_Detected.sql
├── RenameDefaultConstraints.sql
├── Find_Maximum_Float_Values.sql
├── Failed_SQL_Server_Agent_Jobs_With_Restart_Command.sql
├── Get_CPU_Usage_Per_Database.sql
├── MisleadingSQLServerPerformanceCounters.sql
├── Foreign_Keys_With_No_Index.sql
├── Find_Non_Sargable_Queries.sql
├── Numbers_DATALENGTH.sql
├── WhiteListIPTable.sql
├── CPU_Utilization_Graphical_form.sql
├── Checking_Your_Backup_Paths_Exist_and_Automatically_Create_it.sql
├── How_old_your_backups.sql
├── Who_dropped_altered_database_object.sql
├── Cached_Data_Per_Object_in_Memory.sql
├── Get_Opened_Transactions_Info.sql
├── QueryActiveDirectory.sql
├── Disable_Enable_All_Triggers_In_Database.sql
├── Backup_Restore_What’s_My_Status.sql
├── FindDBConnectionLeaks.sql
├── Which_Indexes_are_not_Used.sql
├── FindingImplicitColumnConversionsInPlanCache.sql
├── Finding_Blocking_Queries.sql
├── Queries_with_parallelism.sql
├── Jobs_Get_Runing_info.sql
└── Get_Create_or_Alter_Index_Progress.sql
├── SSMS
├── SSMS_Shortcuts.md
├── SSMS_Tips
│ ├── 05_ALT+Arrow.gif
│ ├── 05_ALT+PASTE.gif
│ ├── AutoRecover_in_SSMS.png
│ ├── ssms_script_objects.gif
│ ├── README.md
│ ├── working_with_tabs_headers.png
│ ├── 25_query_execution_options.png
│ ├── disable_copy_of_empty_text.png
│ ├── import_and_export_settings.png
│ ├── splitting_the_query_window.gif
│ ├── 29_SSMS_Server_Default_Reports.png
│ ├── 32_object_explore_details_01.png
│ ├── 32_object_explore_details_02.png
│ ├── 32_object_explore_details_03.png
│ ├── 38_using_ssms_with_powerbi_01.jpg
│ ├── 38_using_ssms_with_powerbi_02.jpg
│ ├── SQL_Vulnerability_Assessment.gif
│ ├── 24_SSMS_command-line_parameters.png
│ ├── 25_query_execution_options_ansi.png
│ ├── 29_SSMS_Database_Default_Reports.png
│ ├── additional_connection_parameters.png
│ ├── 26_sql_server_diagnostics_extension.png
│ ├── ssms_script_objects_server_version.png
│ ├── 24_changing_what_ssms_opens_on_startup.gif
│ ├── keyboard_shortcuts_for_stored_procedures.png
│ ├── 24_create_solution_commonly_used_sql_scripts.gif
│ ├── 24_changing_what_ssms_opens_on_startup_nosplash.png
│ ├── undock_tabs_and_windows_for_multi_monitor_support.gif
│ ├── 28_connect_to_sql_servers_in_another_domain_using_windows_authentication_with_shortcut.gif
│ └── 28_connect_to_sql_servers_in_another_domain_using_windows_authentication_with_credential.gif
├── SSMS_Snippets
│ ├── Procedure_dynamic_create.sql
│ ├── loop.sql
│ ├── SP_HelpIndex.snippet
│ ├── Dbcc InputBuffer.snippet
│ ├── Count Rows.snippet
│ ├── Index Fragmentation.snippet
│ ├── Count Rows Per Partition.snippet
│ ├── Objects Containing String.snippet
│ ├── Index Usage.snippet
│ ├── Show Current Running Queries.snippet
│ └── Show Current Locks.snippet
└── SSMS_vssettings
│ └── README.md
├── Errors
├── regedit_sqlserver.png
├── Backup
│ ├── Who owns your availability groups.maff
│ ├── Compressed backup errors and TF 3042.maff
│ ├── Unable to restore a backup – Msg 3241.maff
│ ├── Nuance of datetime data type in SQL Server.maff
│ ├── CREATE DATABASE – I’ve not seen that before..maff
│ ├── SQL SERVER - Disabling 15000 Partitions (15k).maff
│ ├── SQL Server 2016 Online ALTER COLUMN Operation.maff
│ ├── Case study Troubleshooting Doomed Transactions.maff
│ ├── Be aware of 701 error if you use memory optimized table variable in a loop.maff
│ ├── SQL SERVER - Logon Failure The User has not Been Granted the Requested Logon Type at This Computer.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
├── PDB
│ └── README.md
└── Identity_gap_sql_server_2012.sql
├── Sample_Databases
├── TSQLV4.sql
├── PerformanceV3.sql
└── Database_script.sql
├── img
└── microsoft-sql-server-logo.png
├── CLR
├── Regex
│ ├── Fill_Factor
│ │ └── InstallRegex.sql
│ └── SqlRegularExpressions_SQLServerProject_QuickDeployment.zip
└── README.md
├── Stored_Procedure
├── dbo.sp_GenerateMerge.sql
├── dbo.sp_Defrag_Indexes.sql
├── dbo.sp_generate_merge.sql
├── Recover_Deleted_Data_Proc.sql
├── dbo.sp_IndexAnalysis-v11.sql
├── dbo.usp_PrintError.sql
├── dbo.usp_FindDbObjects.sql
├── dbo.usp_checkAllDatabases.sql
├── dbo.usp_RandomWait.sql
├── dbo.usp_PrintDebug.sql
├── dbo.sp_FailedLogins.sql
└── dbo.sp_Example_RegisterAssembly_PDFCLR.sql
├── User_Defined_Function
├── udf_IsValidCard.sql
├── udf_PatternSplitLoop.sql
├── udf_Haversine.sql
├── udf_RemoveNonAlphaCharacters.sql
├── dbo.ConvertHexLSN.sql
├── udf_FindPosition.sql
├── udf_SplitStringByDelimiter.sql
├── udf_Tally.sql
├── udf_DateFormattedByMask.sql
├── fnWordDifference.sql
├── udf_INSTR.sql
├── udf_CheckDynamicSQL.sql
└── udf_QueriesWithParameterizationProblems.sql
├── Articles
└── Backup
│ ├── Permissions_Poster_SQL_Server_2012.pdf
│ ├── Permissions_Poster_SQL_Server_2014.pdf
│ ├── Permissions_Poster_SQL_Server_2008_R2.pdf
│ ├── The Curse and Blessings of Dynamic SQL.htm
│ ├── sql server on vmware best practices guide.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
│ ├── To BLOB or Not To BLOB Large Object Storage in a Database or a Filesystem.pdf
│ ├── 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
├── Solution
├── BaselineCollector
│ └── README.md
├── dbWarden
│ └── README.md
├── README.md
├── SysJobHistory
│ ├── seeddata.sql
│ ├── DBA_sysjobhistory_driver.sql
│ ├── DBA_sysjobhistory_config_tbl.sql
│ └── README.md
└── Ola_Maintenance_Solution
│ └── CommandLog.sql
├── .gitignore
├── Extended_Events
├── LoginFailure.sql
├── LockEscalation.sql
├── ImplicitConversionOnly.sql
├── ProcedureWaits.sql
├── XE_Truncate.sql
├── APC_plans_that_are_not_corrected.sql
├── APC_Reverted_plan_corrections.sql
├── Recompile_Histogram.sql
├── AppExecutionTimeout.sql
├── QueryExecutionDetails.sql
├── BackupRestoreTrace.sql
├── ADS_Standard_Azure.sql
├── InvestigateWaits.sql
├── DarkQueries.sql
├── SchemaQueryByUser.sql
├── CheckpointTracking.sql
└── System_Health_Addition.sql
├── PowerShell
├── Disable_Enable_All_Triggers_In_Database.ps1
├── Get-Windows-Block-Size.ps1
├── Compare-Server-Settings.ps1
├── Convert_trc_to_2008r2.ps1
├── Read_XEL_file.ps1
├── Read-XEL-File.ps1
├── ParameterCaseCheck.ps1
├── Get-SQLServerGlobalTraceFlags.ps1
├── Fast_table_to_csv.ps1
├── Export_Query_To_Csv.ps1
├── Parse-TSQL.ps1
└── SQL_Server_table_to_csv.ps1
├── LICENSE
├── Help
└── README.md
└── SQL Server Hints.md
/Scripts/README.md:
--------------------------------------------------------------------------------
1 | # Usefull SQL Server Scripts
2 |
3 | More than 100 useful scripts for SQL Server
4 |
--------------------------------------------------------------------------------
/SSMS/SSMS_Shortcuts.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/SSMS/SSMS_Shortcuts.md
--------------------------------------------------------------------------------
/Errors/regedit_sqlserver.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/Errors/regedit_sqlserver.png
--------------------------------------------------------------------------------
/Sample_Databases/TSQLV4.sql:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/Sample_Databases/TSQLV4.sql
--------------------------------------------------------------------------------
/SSMS/SSMS_Tips/05_ALT+Arrow.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/SSMS/SSMS_Tips/05_ALT+Arrow.gif
--------------------------------------------------------------------------------
/SSMS/SSMS_Tips/05_ALT+PASTE.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/SSMS/SSMS_Tips/05_ALT+PASTE.gif
--------------------------------------------------------------------------------
/Sample_Databases/PerformanceV3.sql:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/Sample_Databases/PerformanceV3.sql
--------------------------------------------------------------------------------
/Scripts/Database_Mail_Problems.sql:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/Scripts/Database_Mail_Problems.sql
--------------------------------------------------------------------------------
/img/microsoft-sql-server-logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/img/microsoft-sql-server-logo.png
--------------------------------------------------------------------------------
/CLR/Regex/Fill_Factor/InstallRegex.sql:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/CLR/Regex/Fill_Factor/InstallRegex.sql
--------------------------------------------------------------------------------
/SSMS/SSMS_Tips/AutoRecover_in_SSMS.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/SSMS/SSMS_Tips/AutoRecover_in_SSMS.png
--------------------------------------------------------------------------------
/SSMS/SSMS_Tips/ssms_script_objects.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/SSMS/SSMS_Tips/ssms_script_objects.gif
--------------------------------------------------------------------------------
/Scripts/Trace_Flag/Trace_Flag_460.sql:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/Scripts/Trace_Flag/Trace_Flag_460.sql
--------------------------------------------------------------------------------
/Stored_Procedure/dbo.sp_GenerateMerge.sql:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/Stored_Procedure/dbo.sp_GenerateMerge.sql
--------------------------------------------------------------------------------
/User_Defined_Function/udf_IsValidCard.sql:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/User_Defined_Function/udf_IsValidCard.sql
--------------------------------------------------------------------------------
/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/working_with_tabs_headers.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/SSMS/SSMS_Tips/working_with_tabs_headers.png
--------------------------------------------------------------------------------
/Stored_Procedure/dbo.sp_Defrag_Indexes.sql:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/Stored_Procedure/dbo.sp_Defrag_Indexes.sql
--------------------------------------------------------------------------------
/Stored_Procedure/dbo.sp_generate_merge.sql:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/Stored_Procedure/dbo.sp_generate_merge.sql
--------------------------------------------------------------------------------
/SSMS/SSMS_Tips/25_query_execution_options.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/SSMS/SSMS_Tips/25_query_execution_options.png
--------------------------------------------------------------------------------
/SSMS/SSMS_Tips/disable_copy_of_empty_text.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/SSMS/SSMS_Tips/disable_copy_of_empty_text.png
--------------------------------------------------------------------------------
/SSMS/SSMS_Tips/import_and_export_settings.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/SSMS/SSMS_Tips/import_and_export_settings.png
--------------------------------------------------------------------------------
/SSMS/SSMS_Tips/splitting_the_query_window.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/SSMS/SSMS_Tips/splitting_the_query_window.gif
--------------------------------------------------------------------------------
/Stored_Procedure/Recover_Deleted_Data_Proc.sql:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/Stored_Procedure/Recover_Deleted_Data_Proc.sql
--------------------------------------------------------------------------------
/Stored_Procedure/dbo.sp_IndexAnalysis-v11.sql:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/Stored_Procedure/dbo.sp_IndexAnalysis-v11.sql
--------------------------------------------------------------------------------
/User_Defined_Function/udf_PatternSplitLoop.sql:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/User_Defined_Function/udf_PatternSplitLoop.sql
--------------------------------------------------------------------------------
/SSMS/SSMS_Tips/29_SSMS_Server_Default_Reports.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/SSMS/SSMS_Tips/29_SSMS_Server_Default_Reports.png
--------------------------------------------------------------------------------
/SSMS/SSMS_Tips/32_object_explore_details_01.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/SSMS/SSMS_Tips/32_object_explore_details_01.png
--------------------------------------------------------------------------------
/SSMS/SSMS_Tips/32_object_explore_details_02.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/SSMS/SSMS_Tips/32_object_explore_details_02.png
--------------------------------------------------------------------------------
/SSMS/SSMS_Tips/32_object_explore_details_03.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/SSMS/SSMS_Tips/32_object_explore_details_03.png
--------------------------------------------------------------------------------
/SSMS/SSMS_Tips/38_using_ssms_with_powerbi_01.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/SSMS/SSMS_Tips/38_using_ssms_with_powerbi_01.jpg
--------------------------------------------------------------------------------
/SSMS/SSMS_Tips/38_using_ssms_with_powerbi_02.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/SSMS/SSMS_Tips/38_using_ssms_with_powerbi_02.jpg
--------------------------------------------------------------------------------
/SSMS/SSMS_Tips/SQL_Vulnerability_Assessment.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/SSMS/SSMS_Tips/SQL_Vulnerability_Assessment.gif
--------------------------------------------------------------------------------
/SSMS/SSMS_Tips/24_SSMS_command-line_parameters.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/SSMS/SSMS_Tips/24_SSMS_command-line_parameters.png
--------------------------------------------------------------------------------
/SSMS/SSMS_Tips/25_query_execution_options_ansi.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/SSMS/SSMS_Tips/25_query_execution_options_ansi.png
--------------------------------------------------------------------------------
/SSMS/SSMS_Tips/29_SSMS_Database_Default_Reports.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/SSMS/SSMS_Tips/29_SSMS_Database_Default_Reports.png
--------------------------------------------------------------------------------
/SSMS/SSMS_Tips/additional_connection_parameters.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/SSMS/SSMS_Tips/additional_connection_parameters.png
--------------------------------------------------------------------------------
/Scripts/Monitor_Deadlocks_with_Extended_Events.sql:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/Scripts/Monitor_Deadlocks_with_Extended_Events.sql
--------------------------------------------------------------------------------
/Articles/Backup/Permissions_Poster_SQL_Server_2012.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/Articles/Backup/Permissions_Poster_SQL_Server_2012.pdf
--------------------------------------------------------------------------------
/Articles/Backup/Permissions_Poster_SQL_Server_2014.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/Articles/Backup/Permissions_Poster_SQL_Server_2014.pdf
--------------------------------------------------------------------------------
/Errors/Backup/Who owns your availability groups.maff:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/Errors/Backup/Who owns your availability groups.maff
--------------------------------------------------------------------------------
/SSMS/SSMS_Tips/26_sql_server_diagnostics_extension.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/SSMS/SSMS_Tips/26_sql_server_diagnostics_extension.png
--------------------------------------------------------------------------------
/SSMS/SSMS_Tips/ssms_script_objects_server_version.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/SSMS/SSMS_Tips/ssms_script_objects_server_version.png
--------------------------------------------------------------------------------
/Errors/Backup/Compressed backup errors and TF 3042.maff:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/Errors/Backup/Compressed backup errors and TF 3042.maff
--------------------------------------------------------------------------------
/Errors/Backup/Unable to restore a backup – Msg 3241.maff:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/Errors/Backup/Unable to restore a backup – Msg 3241.maff
--------------------------------------------------------------------------------
/Articles/Backup/Permissions_Poster_SQL_Server_2008_R2.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/Articles/Backup/Permissions_Poster_SQL_Server_2008_R2.pdf
--------------------------------------------------------------------------------
/Articles/Backup/The Curse and Blessings of Dynamic SQL.htm:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/Articles/Backup/The Curse and Blessings of Dynamic SQL.htm
--------------------------------------------------------------------------------
/SSMS/SSMS_Tips/24_changing_what_ssms_opens_on_startup.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/SSMS/SSMS_Tips/24_changing_what_ssms_opens_on_startup.gif
--------------------------------------------------------------------------------
/SSMS/SSMS_Tips/keyboard_shortcuts_for_stored_procedures.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/SSMS/SSMS_Tips/keyboard_shortcuts_for_stored_procedures.png
--------------------------------------------------------------------------------
/Scripts/SQL Server 2005 Diagnostic Information Queries.sql:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/Scripts/SQL Server 2005 Diagnostic Information Queries.sql
--------------------------------------------------------------------------------
/Scripts/SQL Server 2008 Diagnostic Information Queries.sql:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/Scripts/SQL Server 2008 Diagnostic Information Queries.sql
--------------------------------------------------------------------------------
/Scripts/SQL Server 2012 Diagnostic Information Queries.sql:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/Scripts/SQL Server 2012 Diagnostic Information Queries.sql
--------------------------------------------------------------------------------
/Scripts/SQL Server 2014 Diagnostic Information Queries.sql:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/Scripts/SQL Server 2014 Diagnostic Information Queries.sql
--------------------------------------------------------------------------------
/Scripts/SQL Server 2016 Diagnostic Information Queries.sql:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/Scripts/SQL Server 2016 Diagnostic Information Queries.sql
--------------------------------------------------------------------------------
/Scripts/SQL Server 2017 Diagnostic Information Queries.sql:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/Scripts/SQL Server 2017 Diagnostic Information Queries.sql
--------------------------------------------------------------------------------
/Scripts/SQL Server 2019 Diagnostic Information Queries.sql:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/Scripts/SQL Server 2019 Diagnostic Information Queries.sql
--------------------------------------------------------------------------------
/Articles/Backup/sql server on vmware best practices guide.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/Articles/Backup/sql server on vmware best practices guide.pdf
--------------------------------------------------------------------------------
/Errors/Backup/Nuance of datetime data type in SQL Server.maff:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/Errors/Backup/Nuance of datetime data type in SQL Server.maff
--------------------------------------------------------------------------------
/Scripts/SQL Server 2008 R2 Diagnostic Information Queries.sql:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/Scripts/SQL Server 2008 R2 Diagnostic Information Queries.sql
--------------------------------------------------------------------------------
/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;
--------------------------------------------------------------------------------
/Articles/Backup/Permissions_Poster_SQL_Server_2016_and_SQLDB.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/Articles/Backup/Permissions_Poster_SQL_Server_2016_and_SQLDB.pdf
--------------------------------------------------------------------------------
/Errors/Backup/CREATE DATABASE – I’ve not seen that before..maff:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/Errors/Backup/CREATE DATABASE – I’ve not seen that before..maff
--------------------------------------------------------------------------------
/Errors/Backup/SQL SERVER - Disabling 15000 Partitions (15k).maff:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/Errors/Backup/SQL SERVER - Disabling 15000 Partitions (15k).maff
--------------------------------------------------------------------------------
/Errors/Backup/SQL Server 2016 Online ALTER COLUMN Operation.maff:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/Errors/Backup/SQL Server 2016 Online ALTER COLUMN Operation.maff
--------------------------------------------------------------------------------
/SSMS/SSMS_Tips/24_create_solution_commonly_used_sql_scripts.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/SSMS/SSMS_Tips/24_create_solution_commonly_used_sql_scripts.gif
--------------------------------------------------------------------------------
/Scripts/How_much_will_it_cost_or_save_to_rebuild_that_index.sql:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/Scripts/How_much_will_it_cost_or_save_to_rebuild_that_index.sql
--------------------------------------------------------------------------------
/Scripts/SQL Managed Instance Diagnostic Information Queries.sql:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/Scripts/SQL Managed Instance Diagnostic Information Queries.sql
--------------------------------------------------------------------------------
/Scripts/SQL Server 2016 SP1 Diagnostic Information Queries.sql:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/Scripts/SQL Server 2016 SP1 Diagnostic Information Queries.sql
--------------------------------------------------------------------------------
/Scripts/SQL Server 2016 SP2 Diagnostic Information Queries.sql:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/Scripts/SQL Server 2016 SP2 Diagnostic Information Queries.sql
--------------------------------------------------------------------------------
/Articles/Backup/Permissions_Poster_SQL_Server_vNext_and_SQLDB.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/Articles/Backup/Permissions_Poster_SQL_Server_vNext_and_SQLDB.pdf
--------------------------------------------------------------------------------
/Errors/Backup/Case study Troubleshooting Doomed Transactions.maff:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/Errors/Backup/Case study Troubleshooting Doomed Transactions.maff
--------------------------------------------------------------------------------
/SSMS/SSMS_Tips/24_changing_what_ssms_opens_on_startup_nosplash.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/SSMS/SSMS_Tips/24_changing_what_ssms_opens_on_startup_nosplash.png
--------------------------------------------------------------------------------
/CLR/Regex/SqlRegularExpressions_SQLServerProject_QuickDeployment.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/CLR/Regex/SqlRegularExpressions_SQLServerProject_QuickDeployment.zip
--------------------------------------------------------------------------------
/SSMS/SSMS_Tips/undock_tabs_and_windows_for_multi_monitor_support.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/SSMS/SSMS_Tips/undock_tabs_and_windows_for_multi_monitor_support.gif
--------------------------------------------------------------------------------
/Articles/Backup/SQL Server Performance Tuning in Google Compute Engine.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/Articles/Backup/SQL Server Performance Tuning in Google Compute Engine.pdf
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/Articles/Backup/To BLOB or Not To BLOB Large Object Storage in a Database or a Filesystem.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/Articles/Backup/To BLOB or Not To BLOB Large Object Storage in a Database or a Filesystem.pdf
--------------------------------------------------------------------------------
/Errors/Backup/Be aware of 701 error if you use memory optimized table variable in a loop.maff:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/Errors/Backup/Be aware of 701 error if you use memory optimized table variable in a loop.maff
--------------------------------------------------------------------------------
/Articles/Backup/How to Build a SQL Server Disaster Recovery Plan with Google Compute Engine.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/Articles/Backup/How to Build a SQL Server Disaster Recovery Plan with Google Compute Engine.pdf
--------------------------------------------------------------------------------
/Articles/Backup/Optimizing Your Query Plans with the SQL Server 2014 Cardinality Estimator.docx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/Articles/Backup/Optimizing Your Query Plans with the SQL Server 2014 Cardinality Estimator.docx
--------------------------------------------------------------------------------
/SSMS/SSMS_Tips/28_connect_to_sql_servers_in_another_domain_using_windows_authentication_with_shortcut.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/SSMS/SSMS_Tips/28_connect_to_sql_servers_in_another_domain_using_windows_authentication_with_shortcut.gif
--------------------------------------------------------------------------------
/SSMS/SSMS_Tips/28_connect_to_sql_servers_in_another_domain_using_windows_authentication_with_credential.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/SSMS/SSMS_Tips/28_connect_to_sql_servers_in_another_domain_using_windows_authentication_with_credential.gif
--------------------------------------------------------------------------------
/Errors/Backup/SQL SERVER - Logon Failure The User has not Been Granted the Requested Logon Type at This Computer.maff:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/Errors/Backup/SQL SERVER - Logon Failure The User has not Been Granted the Requested Logon Type at This Computer.maff
--------------------------------------------------------------------------------
/Errors/Backup/SQL SERVER - FIX Error Msg 8672 - The MERGE Statement Attempted to UPDATE or DELETE the Same Row More Than Once.maff:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/Errors/Backup/SQL SERVER - FIX Error Msg 8672 - The MERGE Statement Attempted to UPDATE or DELETE the Same Row More Than Once.maff
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/Errors/Backup/SQL SERVER - FIX Error 913, Severity 16 - Could Not Find Database ID 3. Database May Not be Activated Yet or May be in Transition.maff:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/exajobs/SQL-server-collection/HEAD/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
--------------------------------------------------------------------------------
/Solution/README.md:
--------------------------------------------------------------------------------
1 | # Microsoft SQL Server Solutions
2 |
3 | - [dbWarden](/Solution/dbWarden) a free SQL Server Monitoring Package (by Stevie Rounds and Michael Rounds)
4 | - [Base line Collector script](/Solution/BaselineCollector) (by Robert Virag)
5 | - [Ola Maintenance Solution](/Solution/Ola_Maintenance_Solution) (by Ola Hallengren)
6 | - [SysJobHistory](/Solution/SysJobHistory) (by David Wentzel)
7 |
--------------------------------------------------------------------------------
/Solution/SysJobHistory/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 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Prerequisites
2 | *.d
3 |
4 | # Compiled Object files
5 | *.slo
6 | *.lo
7 | *.o
8 | *.obj
9 |
10 | # Precompiled Headers
11 | *.gch
12 | *.pch
13 |
14 | # Compiled Dynamic libraries
15 | *.so
16 | *.dylib
17 | *.dll
18 |
19 | # Fortran module files
20 | *.mod
21 | *.smod
22 |
23 | # Compiled Static libraries
24 | *.lai
25 | *.la
26 | *.a
27 | *.lib
28 |
29 | # Executables
30 | *.exe
31 | *.out
32 | *.app
33 |
--------------------------------------------------------------------------------
/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;
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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/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/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/Get_SQLServer_Startup_Parameters.sql:
--------------------------------------------------------------------------------
1 | DECLARE @RegHive VARCHAR(50),
2 | @RegKey VARCHAR(100);
3 |
4 | SET @RegHive = 'HKEY_LOCAL_MACHINE';
5 | SET @RegKey = 'Software\Microsoft\MSSQLSERVER\MSSQLServer\Parameters';
6 |
7 | -- Get all of the arguments / parameters when starting up the service.
8 | DECLARE @SQLArgs TABLE (
9 | Value VARCHAR(50),
10 | Data VARCHAR(500),
11 | ArgNum AS CONVERT(INTEGER, REPLACE(Value, 'SQLArg', '')));
12 |
13 | INSERT INTO @SQLArgs
14 | EXECUTE master.sys.xp_instance_regenumvalues @RegHive, @RegKey;
15 |
16 | SELECT * FROM @SQLArgs;
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/Scripts/Get_SQL_Server_Backup_Directory.sql:
--------------------------------------------------------------------------------
1 | DECLARE @HkeyLocal nvarchar(18) = N'HKEY_LOCAL_MACHINE';
2 | DECLARE @MSSqlServerRegPath nvarchar(31) = N'SOFTWARE\Microsoft\MSSQLServer';
3 | DECLARE @InstanceRegPath sysname = @MSSqlServerRegPath + N'\MSSQLServer';
4 |
5 | DECLARE @BackupDirectory nvarchar(512)
6 | if 1=isnull(cast(SERVERPROPERTY('IsLocalDB') as bit), 0)
7 | SET @BackupDirectory=cast(SERVERPROPERTY('instancedefaultdatapath') as nvarchar(512))
8 | else
9 | EXEC master.dbo.xp_instance_regread @HkeyLocal, @InstanceRegPath, N'BackupDirectory', @BackupDirectory OUTPUT;
10 |
11 | SELECT @BackupDirectory AS SQLServerBackupDirectory;
12 |
--------------------------------------------------------------------------------
/Scripts/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 |
--------------------------------------------------------------------------------
/Extended_Events/LockEscalation.sql:
--------------------------------------------------------------------------------
1 | /*
2 | https://littlekendra.com/2017/04/03/which-locks-count-toward-lock-escalation/
3 | by Kendra Little Melton 2017-04-03
4 | */
5 |
6 | DROP EVENT SESSION LockEscalation ON SERVER;
7 | GO
8 |
9 | CREATE EVENT SESSION LockEscalation ON SERVER
10 | ADD EVENT sqlserver.lock_escalation(SET collect_database_name=(1),collect_statement=(1)
11 | ACTION(sqlserver.session_id))
12 | ADD TARGET package0.event_file(SET filename=N'C:\XE\Lock_Escalation.xel')
13 | WITH (MAX_MEMORY=4096 KB,EVENT_RETENTION_MODE=NO_EVENT_LOSS,MAX_DISPATCH_LATENCY=5 SECONDS,MAX_EVENT_SIZE=0 KB,MEMORY_PARTITION_MODE=NONE,TRACK_CAUSALITY=OFF,STARTUP_STATE=OFF)
14 | GO
15 |
--------------------------------------------------------------------------------
/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 );
--------------------------------------------------------------------------------
/Scripts/PIVOT_Columns_generator.sql:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | Generate numeric columns for PIVOT statement
4 | 1 column
5 | No
6 | 2020-01-23 by Konstantin Taranov
7 | 1.0
8 | https://github.com/ktaranov/sqlserver-kit/blob/master/Scripts/PIVOT_Columns_generator.sql
9 |
10 | */
11 |
12 | DECLARE @i int = 1990;
13 | DECLARE @s varchar(max) = '';
14 | DECLARE @sep varchar(10) = ', ';
15 |
16 | WHILE @i <= 2020
17 | BEGIN
18 | SET @s = @s + '[' + CAST(@i AS varchar) + ']' + @sep;
19 | SET @i = @i + 1;
20 | END;
21 |
22 | SELECT LEFT(@s, DATALENGTH(@s) - DATALENGTH(@sep)) AS y;
23 |
--------------------------------------------------------------------------------
/Stored_Procedure/dbo.usp_PrintError.sql:
--------------------------------------------------------------------------------
1 | IF OBJECT_ID('[dbo].[usp_PrintError]', 'P') IS NULL
2 | EXECUTE('CREATE PROCEDURE [dbo].[usp_PrintError] AS SELECT 1');
3 | go
4 |
5 |
6 | ALTER PROCEDURE [dbo].[usp_PrintError]
7 | AS
8 | BEGIN
9 | SET NOCOUNT ON;
10 |
11 | -- Print error information.
12 | PRINT 'Error: ' + CONVERT(varchar(50), ERROR_NUMBER()) +
13 | ', Severity: ' + CONVERT(varchar(5), ERROR_SEVERITY()) +
14 | ', State: ' + CONVERT(varchar(5), ERROR_STATE()) +
15 | ', Procedure: ' + ISNULL(ERROR_PROCEDURE(), '-') +
16 | ', Line: ' + CONVERT(varchar(5), ERROR_LINE()) +
17 | ', User name: ' + CONVERT(sysname, CURRENT_USER);
18 | PRINT ERROR_MESSAGE();
19 | END;
20 | go
21 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/Scripts/Remove_Leading_and_Trailing_Backward_and_Forward_Slashes.sql:
--------------------------------------------------------------------------------
1 | /*
2 | https://sqlperformance.com/2019/10/t-sql-queries/overlooked-t-sql-gems
3 | */
4 |
5 | SELECT string, leading_slash_count, trailing_slash_count,
6 | STUFF(STUFF(string, LEN(string) - trailing_slash_count + 1,
7 | trailing_slash_count, ''), 1, leading_slash_count, '') AS new_string
8 | FROM ( VALUES
9 | (CAST('//\\ remove leading and trailing backward (\) and forward (/) slashes \\//' AS varchar(200))),
10 | ('//\\**remove leading and trailing backward (\) and forward (/) slashes**\\//')
11 | ) AS test_data(string)
12 | CROSS APPLY (
13 | SELECT PATINDEX('%[^/\]%', string) - 1 AS leading_slash_count,
14 | PATINDEX('%[^/\]%', REVERSE(string)) - 1 AS trailing_slash_count
15 | ) AS ca1;
16 |
--------------------------------------------------------------------------------
/Scripts/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;
--------------------------------------------------------------------------------
/Extended_Events/ImplicitConversionOnly.sql:
--------------------------------------------------------------------------------
1 | /*
2 | Original link: https://www.scarydba.com/2018/10/15/using-extended-events-to-capture-implicit-conversions/
3 | Author: Grant Fritchey
4 | */
5 | -- If the Event Session exists DROP it
6 | IF EXISTS (SELECT 1
7 | FROM sys.server_event_sessions
8 | WHERE name = N'ImplicitConversionOnly')
9 | DROP EVENT SESSION ImplicitConversionOnly ON SERVER;
10 |
11 | CREATE EVENT SESSION ImplicitConversionOnly
12 | ON SERVER
13 | ADD EVENT sqlserver.plan_affecting_convert
14 | (ACTION (sqlserver.sql_text)
15 | -- WHERE (sqlserver.equal_i_sql_unicode_string(sqlserver.database_name, N'AdventureWorks2017'))
16 | )
17 | ADD TARGET package0.event_file
18 | (SET filename = N'ImplicitConversionOnly');
19 |
20 | ALTER EVENT SESSION ImplicitConversionOnly ON SERVER STATE = START;
21 | GO
22 |
--------------------------------------------------------------------------------
/PowerShell/Disable_Enable_All_Triggers_In_Database.ps1:
--------------------------------------------------------------------------------
1 | #requires -version 5.0
2 | #requires -modules dbatools
3 |
4 | <#
5 | .SYNOPSIS
6 | Disable and enable again all triggers in database
7 |
8 | .DESCRIPTION
9 | Disable and enable again all triggers in database
10 | https://jesspomfret.com/disable-all-triggers/
11 |
12 | .PARAMETER database
13 | Database name
14 | #>
15 |
16 | $database = "AdventureWorks2017";
17 | $svr = Connect-DbaInstance -SqlInstance server1;
18 | $foreach ($tbl in $svr.databases[$database].Tables)
19 | {
20 | foreach ($tr in $($tbl.Triggers | Where-Object Isenabled)) {
21 | $triggers += $tr | Select-Object @{l='SchemaName';e={$tbl.Schema}}, @{l='TableName';e={$tbl.name}}, @{l='TriggerName';e={$_.name}};
22 | $tr.isenabled = $FALSE;
23 | $tr.alter();
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/Extended_Events/ProcedureWaits.sql:
--------------------------------------------------------------------------------
1 | /*
2 | Original link: https://www.scarydba.com/2018/02/05/wait-statistics-query/
3 | Author: Grant Fritchey
4 | */
5 |
6 | CREATE EVENT SESSION ProcedureWaits
7 | ON SERVER
8 | ADD EVENT sqlos.wait_completed
9 | (SET collect_wait_resource = (1)
10 | WHERE (sqlserver.equal_i_sql_unicode_string(sqlserver.database_name, N'AdventureWorks2017'))),
11 | ADD EVENT sqlserver.module_end
12 | (WHERE ( sqlserver.database_name = N'AdventureWorks2017'
13 | AND object_name = N'ProductTransactionHistoryByReference')),
14 | ADD EVENT sqlserver.rpc_completed
15 | (WHERE (sqlserver.database_name = N'AdventureWorks2017')),
16 | ADD EVENT sqlserver.rpc_starting
17 | (WHERE (sqlserver.database_name = N'AdventureWorks2017'))
18 | WITH (TRACK_CAUSALITY = ON);
19 |
--------------------------------------------------------------------------------
/Scripts/Line_Of_Codes_In_database.sql:
--------------------------------------------------------------------------------
1 | /*
2 | Author: Pinal Dave
3 | Source link: https://blog.sqlauthority.com/2015/06/12/sql-server-how-many-line-of-code-do-you-have-in-database/
4 | */
5 |
6 | SELECT DB_NAME(DB_ID()) AS DBName,
7 | ObjectType,
8 | COUNT(*) AS Object_Count,
9 | SUM(LinesOfCode) AS LinesOfCode
10 | FROM (SELECT s.type AS ObjectType,
11 | LEN(definition)- LEN(REPLACE(definition,CHAR(10),'')) AS LinesOfCode,
12 | OBJECT_NAME(a.object_id) AS NameOfObject
13 | FROM sys.all_sql_modules AS a
14 | INNER JOIN sysobjects AS s
15 | ON a.object_id = s.id
16 | -- AND xtype IN('TR', 'P', 'FN', 'IF', 'TF', 'V')
17 | WHERE OBJECTPROPERTY(a.object_id,'IsMSShipped') = 0
18 | ) SubQuery
19 | GROUP BY ObjectType;
20 |
--------------------------------------------------------------------------------
/User_Defined_Function/udf_RemoveNonAlphaCharacters.sql:
--------------------------------------------------------------------------------
1 | IF OBJECT_ID('dbo.udf_RemoveNonAlphaCharacters') IS NULL
2 | EXECUTE ('CREATE FUNCTION dbo.udf_RemoveNonAlphaCharacters() RETURNS NVARCHAR(MAX) AS RETURN SELECT 1 AS A;');
3 | GO
4 |
5 |
6 | ALTER FUNCTION dbo.udf_RemoveNonAlphaCharacters(
7 | @inputString NVARCHAR(MAX)
8 | , @keepValues NVARCHAR(1000) = N'%[^a-z0-9]%'
9 | )
10 | RETURNS NVARCHAR(MAX)
11 | /*
12 | SELECT dbo.udf_RemoveNonAlphaCharacters(N'Тестовая строка - Test string 123_456', N'%[^a-z0-9]%');
13 | SELECT dbo.udf_RemoveNonAlphaCharacters(N'Тестовая строка - Test string 123_456', N'%[^3-9]%');
14 | */
15 | AS
16 | BEGIN
17 | WHILE PATINDEX(@keepValues, @inputString) > 0
18 | SET @inputString = STUFF(@inputString, PATINDEX(@keepValues, @inputString), 1, '');
19 |
20 | RETURN @inputString;
21 | END;
22 | GO
23 |
--------------------------------------------------------------------------------
/Stored_Procedure/dbo.usp_FindDbObjects.sql:
--------------------------------------------------------------------------------
1 | CREATE PROCEDURE [dbo].[usp_FindDbObjects]
2 | @string NVARCHAR(MAX) = ''
3 | AS
4 | BEGIN
5 |
6 | SET NOCOUNT ON
7 | SET ANSI_WARNINGS OFF
8 |
9 | -- Returns list of DB objects containing the string in their definition and/or in their name.
10 | SELECT [DB_ObjName] = OBJECT_SCHEMA_NAME(sm.[object_id]) + '.' + OBJECT_NAME(sm.[object_id]), so.type_desc [DB_ObjType],
11 | (LEN(sm.[definition]) - LEN(REPLACE(sm.[definition], CHAR(10), ''))) Lines_of_Code
12 | FROM SYS.SQL_MODULES sm
13 | INNER JOIN SYS.OBJECTS so
14 | ON sm.[OBJECT_ID] = so.[OBJECT_ID]
15 | WHERE sm.[definition] LIKE N'%' + @string + '%'
16 | OR so.[name] like N'%' + @string + '%'
17 | GROUP BY sm.[object_id], so.type_desc,sm.[definition]
18 | ORDER BY [DB_ObjName], [DB_ObjType];
19 |
20 | SET NOCOUNT OFF
21 | SET ANSI_WARNINGS ON
22 |
23 | END
--------------------------------------------------------------------------------
/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/Trace_Flag/Trace_Flag_8726.sql:
--------------------------------------------------------------------------------
1 | /*
2 | Trace Flag Demo: 8726
3 | !!! Undocumented trace flag !!!
4 | Function: Disables the heuristic that discourages the optimizer from producing an index union plan.
5 | SQL Server Version: ?
6 | Information link: https://github.com/ktaranov/sqlserver-kit/blob/master/SQL%20Server%20Trace%20Flag.md#8726
7 | */
8 |
9 | USE StackOverflow2010;
10 | GO
11 |
12 | /* Execution Plan: https://www.brentozar.com/pastetheplan/?id=B1mSzXGv8 */
13 | /* No index union (seek on Users, multiple scans on Comments) */
14 | SELECT *
15 | FROM Users u
16 | LEFT JOIN Comments c
17 | ON u.Id = c.UserId
18 | OR u.Id = c.PostId
19 | WHERE u.DisplayName = 'alex';
20 |
21 | /* Gets the index union plan */
22 | SELECT *
23 | FROM Users u
24 | LEFT JOIN Comments c
25 | ON u.Id = c.UserId
26 | OR u.Id = c.PostId
27 | WHERE u.DisplayName = 'alex'
28 | OPTION (QUERYTRACEON 8726);
29 |
--------------------------------------------------------------------------------
/Scripts/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/Get_SQL_Server_Agent_Information.sql:
--------------------------------------------------------------------------------
1 | /*
2 | Author: sqlity.net
3 | Source link: http://sqlity.net/en/1868/identify-sql-server-service-account-in-t-sql/
4 | */
5 |
6 | IF CAST(SERVERPROPERTY('ProductMajorVersion') AS INT) < 10
7 | BEGIN
8 | DECLARE @sn NVARCHAR(128);
9 | EXEC master.dbo.xp_regread
10 | 'HKEY_LOCAL_MACHINE',
11 | 'SYSTEM\CurrentControlSet\services\SQLSERVERAGENT',
12 | 'ObjectName',
13 | @sn OUTPUT;
14 | SELECT @sn;
15 | END;
16 | ELSE
17 | BEGIN
18 | SELECT DSS.servicename
19 | , DSS.startup_type_desc
20 | , DSS.status_desc
21 | , DSS.last_startup_time
22 | , DSS.service_account
23 | , DSS.is_clustered
24 | , DSS.cluster_nodename
25 | , DSS.filename
26 | , DSS.startup_type
27 | , DSS.status
28 | , DSS.process_id
29 | FROM sys.dm_server_services AS DSS;
30 | END;
31 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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/How_to_obtain_the_deadlocks_on_Azure.sql:
--------------------------------------------------------------------------------
1 | /*
2 | Author: Jose M Jurado
3 | Created Date: 2017-01-21
4 | Original link: https://blogs.msdn.microsoft.com/azuresqldbsupport/2017/01/21/lesson-learned-19-how-to-obtain-the-deadlocks-of-your-azure-sql-database/
5 | Source link: https://github.com/ktaranov/sqlserver-kit/blob/master/Scripts/How_to_obtain_the_deadlocks_on_Azure.sql
6 | Modified: 2019-03-18 by Konstantin Taranov
7 | */
8 |
9 | USE master;
10 | GO
11 |
12 | WITH CTE AS (
13 | SELECT CAST(event_data AS XML) AS [target_data_XML]
14 | FROM sys.fn_xe_telemetry_blob_target_read_file('dl', null, null, null)
15 | )
16 | SELECT target_data_XML.value('(/event/@timestamp)[1]', 'DateTime2') AS [Timestamp]
17 | , target_data_XML.query('/event/data[@name=''xml_report'']/value/deadlock') AS deadlock_xml
18 | , target_data_XML.query('/event/data[@name=''database_name'']/value').value('(/value)[1]', 'nvarchar(100)') AS [db_name]
19 | FROM CTE;
20 |
--------------------------------------------------------------------------------
/Scripts/Extract_Scale_Part_From_Decimal_Number.sql:
--------------------------------------------------------------------------------
1 | /*
2 | Author: Pinal Dave
3 | Created Date: 2018-09-12
4 | Original link: https://blog.sqlauthority.com/2018/09/12/sql-server-simple-method-to-extract-scale-part-from-decimal-number/
5 | Source link: https://github.com/ktaranov/sqlserver-kit/blob/master/Scripts/Extract_Scale_Part_From_Decimal_Number.sql
6 | Modified: 2018-01-29 by Konstantin Taranov
7 | */
8 |
9 | IF OBJECT_ID(N'tempdb..#Numbers', 'U') IS NOT NULL DROP TABLE #Numbers;
10 |
11 | CREATE TABLE #Numbers (DecimalValue DECIMAL(16, 10) NOT NULL);
12 |
13 | INSERT INTO #Numbers(DecimalValue) VALUES (100.0000000001);
14 | INSERT INTO #Numbers(DecimalValue) VALUES (-23.8900000098);
15 | INSERT INTO #Numbers(DecimalValue) VALUES (390.077);
16 | INSERT INTO #Numbers(DecimalValue) VALUES (12.87);
17 | INSERT INTO #Numbers(DecimalValue) VALUES (390.1);
18 |
19 | SELECT DecimalValue
20 | , ABS(DecimalValue)%1 AS DecimalScale
21 | FROM #Numbers;
22 | GO
23 |
--------------------------------------------------------------------------------
/Scripts/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
--------------------------------------------------------------------------------
/Extended_Events/XE_Truncate.sql:
--------------------------------------------------------------------------------
1 | /*
2 | https://www.sqlservercentral.com/forums/topic/extended-events-capture-truncate-using-object_altered-event
3 | by Evgeny Garaev 2018-06-28
4 | */
5 |
6 | /* Stop trace if started */
7 | IF EXISTS (SELECT * FROM sys.dm_xe_sessions WHERE name = N'XE_Truncate')
8 | ALTER EVENT SESSION XE_Truncate ON SERVER STATE = STOP;
9 |
10 | /* Delete trace if exists */
11 | IF EXISTS (SELECT * FROM sys.server_event_sessions WHERE name = N'XE_Truncate')
12 | DROP EVENT SESSION XE_Truncate ON SERVER;
13 |
14 |
15 | CREATE EVENT SESSION XE_Truncate ON SERVER
16 | ADD EVENT sqlserver.sp_statement_starting(SET collect_statement=(1)
17 | WHERE ([sqlserver].[like_i_sql_unicode_string]([statement], N'truncate table%'))),
18 | ADD EVENT sqlserver.sql_statement_starting(SET collect_statement=(1)
19 | WHERE ([sqlserver].[like_i_sql_unicode_string]([statement],N'truncate table%')));
20 | GO
21 |
22 | ALTER EVENT SESSION XE_Truncate ON SERVER STATE = START;
23 | GO
24 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/SSMS/SSMS_vssettings/README.md:
--------------------------------------------------------------------------------
1 | # SSMS settings files
2 | In files with `_Default_` you can find defaults SSMS settings for different SSMS version.
3 | For import settings files see **tip 1** in [SSMS tips](https://github.com/ktaranov/sqlserver-kit/blob/master/SSMS/SSMS_Tips.md#1) guide.
4 |
5 | My awesome settings: [ktaranov_18.7.1.vssettings](.ktaranov_18.7.1.vssettings)
6 |
7 | - [AB.DarkScheme.LargeFonts.vssettings](/AB.DarkScheme.LargeFonts.vssettings)
8 | - [AB.DarkScheme.NormalFonts.vssettings](/AB.DarkScheme.NormalFonts.vssettings)
9 | - [NewSettings_17.2(14.0.17177).vssettings](/NewSettings_17.2(14.0.17177).vssettings)
10 | - [NewSettings_2014(12.0.5556).vssettings](/NewSettings_2014(12.0.5556).vssettings)
11 | - [NewSettings_Default_17.2(14.0.17177).vssettings](/NewSettings_Default_17.2(14.0.17177).vssettings)
12 | - [NewSettings_Default_18.7.1(15.0.18358).vssettings](/NewSettings_Default_18.7.1(15.0.18358).vssettings)
13 | - [NewSettings_Default_2014(12.0.5556).vssettings](/NewSettings_Default_2014(12.0.5556).vssettings)
14 |
--------------------------------------------------------------------------------
/Scripts/Trace_Flag/Trace_Flag_8727.sql:
--------------------------------------------------------------------------------
1 | /*
2 | Trace Flag Demo: 8727
3 | !!! Undocumented trace flag !!!
4 | Function: Can be used to prevent unwanted index union plans.
5 | SQL Server Version: ?
6 | Information link: https://github.com/ktaranov/sqlserver-kit/blob/master/SQL%20Server%20Trace%20Flag.md#8727
7 | */
8 |
9 | USE StackOverflow2010;
10 | GO
11 |
12 | /* Execution Plan: https://www.brentozar.com/pastetheplan/?id=HkwhlQGwL */
13 | /* Gets an index union plan normally */
14 | SELECT *
15 | FROM dbo.Users u
16 | OUTER APPLY
17 | (
18 | SELECT *
19 | FROM dbo.Comments c
20 | WHERE
21 | u.Id = c.UserId
22 | OR u.Id = c.PostId
23 | ) c
24 | WHERE u.DisplayName = 'alex';
25 |
26 | /* No index union (seek on Users, multiple scans on Comments) */
27 | SELECT *
28 | FROM dbo.Users u
29 | OUTER APPLY
30 | (
31 | SELECT *
32 | FROM dbo.Comments c
33 | WHERE
34 | u.Id = c.UserId
35 | OR u.Id = c.PostId
36 | ) c
37 | WHERE u.DisplayName = 'alex'
38 | OPTION (QUERYTRACEON 8727);
39 |
--------------------------------------------------------------------------------
/Scripts/Visualizing_VLF.sql:
--------------------------------------------------------------------------------
1 | /*
2 | Author: Steve Stedman
3 | Original link: http://stevestedman.com/2016/10/visualizing-vlfs-updated/
4 | */
5 |
6 | DECLARE @logInfoResults AS TABLE
7 | (
8 | [RecoveryUnitId] BIGINT, -- only on SQL Server 2012 and newer
9 | [FileId] TINYINT,
10 | [FileSize] BIGINT,
11 | [StartOffset] BIGINT,
12 | [FSeqNo] INTEGER,
13 | [Status] TINYINT,
14 | [Parity] TINYINT,
15 | [CreateLSN] NUMERIC(38,0)
16 | );
17 |
18 | INSERT INTO @logInfoResults
19 | EXEC sp_executesql N'DBCC LOGINFO WITH NO_INFOMSGS';
20 |
21 | SELECT cast(FileSize / 1024.0 / 1024 AS DECIMAL(20,1)) as FileSizeInMB
22 | , CASE WHEN FSeqNo = 0 THEN 'Available - Never Used'
23 | ELSE (CASE WHEN [Status] = 2 THEN 'In Use' ELSE 'Available' END)
24 | END AS TextStatus
25 | , [Status]
26 | , REPLICATE('x', FileSize / MIN(FileSize) over()) as [BarChart ________________________________________________________________________________________________]
27 | FROM @logInfoResults;
28 | GO
29 |
--------------------------------------------------------------------------------
/User_Defined_Function/dbo.ConvertHexLSN.sql:
--------------------------------------------------------------------------------
1 | IF OBJECT_ID('dbo.udf_ConvertHexLSN') IS NULL
2 | EXECUTE ('CREATE FUNCTION udf_ConvertHexLSN() RETURNS TABLE AS RETURN SELECT 1 AS A;');
3 | GO
4 |
5 |
6 | ALTER FUNCTION dbo.udf_ConvertHexLSN(
7 | @lsnc varchar(25)
8 | )
9 | /*
10 | Author: Max Vernon
11 | Original link: https://www.sqlserverscience.com/internals/convert-lsn-hex-decimal/
12 |
13 | SELECT * FROM dbo.udf_ConvertHexLSN('00000268:0000356c:0001');
14 | */
15 | RETURNS TABLE
16 | WITH SCHEMABINDING
17 | AS
18 | RETURN
19 | (
20 | SELECT TOP(1)
21 | LSNd = CONVERT(varchar(8), CONVERT(int, CONVERT(varbinary(8), '0x' + CONVERT(varchar(10), LEFT(@lsnc, 8), 0), 1), 1))
22 | + ':' + CONVERT(varchar(8), CONVERT(int, CONVERT(varbinary(8), '0x' + CONVERT(varchar(10), SUBSTRING(@lsnc, 10, 8), 0), 1)), 1)
23 | + ':' + CONVERT(varchar(8), CONVERT(int, CONVERT(varbinary(8), '0x' + CONVERT(varchar(10), RIGHT(@lsnc, 4), 0), 1), 1))
24 | );
25 | GO
26 |
--------------------------------------------------------------------------------
/Scripts/glen_berry_diagnostic_queries_links.txt:
--------------------------------------------------------------------------------
1 | https://www.dropbox.com/s/k1vauzxxhyh1fnb/SQL%20Server%202019%20Diagnostic%20Information%20Queries.sql?dl=1
2 | https://www.dropbox.com/s/3ix2lqhry34c5wy/SQL%20Server%202017%20Diagnostic%20Information%20Queries.sql?dl=1
3 | https://www.dropbox.com/s/pkpxihdkq3odgbj/SQL%20Server%202016%20SP2%20Diagnostic%20Information%20Queries.sql?dl=1
4 | https://www.dropbox.com/s/w6gi8j76k64fgbg/SQL%20Server%202016%20SP1%20Diagnostic%20Information%20Queries.sql?dl=1
5 | https://www.dropbox.com/s/uttp0843e5078vs/SQL%20Server%202014%20Diagnostic%20Information%20Queries.sql?dl=1
6 | https://www.dropbox.com/s/3l4yotzedk45xeh/SQL%20Server%202012%20Diagnostic%20Information%20Queries.sql?dl=1
7 | https://www.dropbox.com/s/fq6hyw899fe3crv/SQL%20Server%202008%20R2%20Diagnostic%20Information%20Queries.sql?dl=1
8 | https://www.dropbox.com/s/mjxw1w9tgw7eo6g/SQL%20Server%202008%20Diagnostic%20Information%20Queries.sql?dl=1
9 | https://www.dropbox.com/s/3kkskuheyzauih9/SQL%20Server%202005%20Diagnostic%20Information%20Queries.sql?dl=1
10 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/Scripts/Table_Count_Fast_Alternatives.sql:
--------------------------------------------------------------------------------
1 | -- source: http://www.brentozar.com/archive/2014/02/count-number-rows-table-sql-server/
2 | DECLARE @TableName sysname = N'bigTransactionHistory';
3 |
4 | SELECT TBL.object_id
5 | , TBL.name
6 | , SUM(PART.rows) AS NumberOfRows
7 | FROM sys.tables AS TBL
8 | INNER JOIN sys.partitions AS PART ON TBL.object_id = PART.object_id
9 | INNER JOIN sys.indexes AS IDX ON PART.object_id = IDX.object_id
10 | AND PART.index_id = IDX.index_id
11 | WHERE TBL.name = @TableName
12 | AND IDX.index_id < 2
13 | GROUP BY TBL.object_id, TBL.name;
14 |
15 |
16 | DECLARE @tableName sysname = N'bigTransactionHistory';
17 |
18 | SELECT object_id
19 | , SCHEMA_NAME(object_id) AS SchemaName
20 | , OBJECT_NAME(object_id) AS TableName
21 | , SUM(row_count) AS NumberOfRows
22 | FROM sys.dm_db_partition_stats
23 | WHERE object_id = OBJECT_ID(@tableName) AND index_id < 2
24 | GROUP BY object_id
25 | , SCHEMA_NAME(object_id)
26 | , OBJECT_NAME(object_id);
27 |
--------------------------------------------------------------------------------
/Scripts/When_SQL_Server_Was_Installed.sql:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | When SQL Server Was Installed.
4 | Find in sys.server_principals oldest NT Service login.
5 | No
6 | Rebecca Lewis
7 | 2019-04-25
8 | 2019-04-30 by Konstantin Taranov
9 | 1.0
10 | https://github.com/ktaranov/sqlserver-kit/blob/master/Scripts/When_SQL_Server_Was_Installed.sql
11 |
12 | */
13 |
14 |
15 | SELECT TOP(1)
16 | SERVERPROPERTY('ProductVersion') AS ProductVersion
17 | , SERVERPROPERTY('ProductLevel') AS ProductLevel
18 | , SERVERPROPERTY('Edition') AS Edition
19 | , SERVERPROPERTY('MachineName') AS MachineName
20 | , create_date AS "SQL Server Installation Date"
21 | , name AS SystemUserName
22 | FROM sys.server_principals
23 | WHERE name LIKE 'NT Service%'
24 | ORDER BY create_date;
25 |
--------------------------------------------------------------------------------
/Scripts/Fast_alternative_to_sp_WhoIsActive.sql:
--------------------------------------------------------------------------------
1 | /*
2 | Author: Arthur Daniels
3 | Created Date: 2019-01-29
4 | Original link: https://blog.sqlauthority.com/2018/09/12/sql-server-simple-method-to-extract-scale-part-from-decimal-number/
5 | Source link: https://github.com/ktaranov/sqlserver-kit/blob/master/Scripts/Fast_alternative_to_sp_WhoIsActive.sql
6 | Modified: 2018-01-29 by Konstantin Taranov
7 | */
8 |
9 | SELECT s.session_id,
10 | r.start_time,
11 | s.host_name,
12 | s.login_name,
13 | i.event_info,
14 | r.status,
15 | s.program_name,
16 | r.writes,
17 | r.reads,
18 | r.logical_reads,
19 | r.blocking_session_id,
20 | r.wait_type,
21 | r.wait_time,
22 | r.wait_resource
23 | FROM sys.dm_exec_requests AS r
24 | INNER JOIN sys.dm_exec_sessions AS s ON s.session_id = r.session_id
25 | CROSS APPLY sys.dm_exec_input_buffer(s.session_id, r.request_id) as i
26 | WHERE s.session_id <> @@SPID AND
27 | s.is_user_process = 1;
28 | --Remove the line above if you want to see system processes
29 |
--------------------------------------------------------------------------------
/Scripts/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 |
--------------------------------------------------------------------------------
/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
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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/Dynamic_GRANT_Generation.sql:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | Dynamically generate GRANTs.
4 | PRINT dynamically generated GRANTs for user.
5 | ?
6 | 2020-02-08 by Konstantin Taranov
7 | 1.0
8 | https://github.com/ktaranov/sqlserver-kit/blob/master/Scripts/Dynamic_GRANT_Generation.sql
9 |
10 | */
11 |
12 |
13 | SET NOCOUNT ON;
14 | SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
15 |
16 | DECLARE @userName sysname = QUOTENAME(N'user_name');
17 | DECLARE @tsql nvarchar(max) = N'';
18 |
19 | SELECT @tsql = @tsql + 'GRANT SELECT, INSERT, UPDATE, DELETE ON ' +
20 | QUOTENAME(SCHEMA_NAME("schema_id")) + N'.' +
21 | QUOTENAME("name") + N' TO ' + @userName + N';' + CHAR(13) + CHAR(10)
22 | FROM sys.tables
23 | /*
24 | WHERE "name" NOT IN ('')
25 | --*/
26 | ;
27 |
28 | IF LEN(@tsql) <= 8000
29 | BEGIN
30 | PRINT(@tsql);
31 | END;
32 | ELSE
33 | BEGIN
34 | SELECT @tsql;
35 | END;
36 |
--------------------------------------------------------------------------------
/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/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 |
--------------------------------------------------------------------------------
/Scripts/Restore_Database_Dynamic_SQL.sql:
--------------------------------------------------------------------------------
1 | USE master;
2 | GO
3 |
4 | DECLARE @restoreStatement NVARCHAR(4000) = N'';
5 | DECLARE @databaseName SYSNAME = N'AdventureWorks2014';
6 | DECLARE @backupFilePath NVARCHAR(2000) = N'G:\YaDisk\Backup\Distrib\SQL Server\Sample_Database\AdventureWorks\' + @databaseName + N'.bak';
7 | DECLARE @serverPath NVARCHAR(2000) = N'K:\MSSQL\MSSQL14.MSSQLSERVER\MSSQL\DATA\';
8 | DECLARE @debug BIT = 1;
9 |
10 | SET @restoreStatement = N'
11 | RESTORE DATABASE [@databaseName] FROM DISK = N''@backupFilePath''
12 | WITH FILE = 1, MOVE N''@databaseName_Data'' TO N''@serverPath@databaseName_Data.mdf'',
13 | MOVE N''@databaseName_Log'' TO N''@serverPath@databaseName_Log.ldf'', NOUNLOAD, STATS = 5';
14 | SET @restoreStatement = REPLACE(@restoreStatement, '@databaseName', @databaseName);
15 | SET @restoreStatement = REPLACE(@restoreStatement, '@backupFilePath', @backupFilePath);
16 | SET @restoreStatement = REPLACE(@restoreStatement, '@serverPath', @serverPath);
17 |
18 | IF @debug = 1 PRINT(@restoreStatement)
19 | ELSE
20 | EXEC sp_executesql @restoreStatement;
21 | GO
22 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2015-2021 Konstantin Taranov
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/Help/README.md:
--------------------------------------------------------------------------------
1 | # SQL Help
2 |
3 | Need free help? Just follow this simple step:
4 | 1. [Join GitHub](https://github.com/join)
5 | 2. Add star to this repo
6 | 3. Open new issue with a detailed explanation of your problem
7 |
8 | ## How to ask right?
9 |
10 | 1. [Create issue](https://github.com/ktaranov/sqlserver-kit/issues/new) in this repo or question on stackoverflow.com
11 | 2. Include:
12 | 1. Operation system with detailed version (Windows, Ubuntu, Macos etc.). Example: `Microsoft Windows [Version 10.0.16299.248]`
13 | 2. Relation database type (SQL Server preferred, Orcale, MySQL, PostgreSQL, SQLite etc.) with detailed version. Example: `Microsoft SQL Server 2017 (RTM-CU1) (KB4038634) - 14.0.3006.16 (X64) ... on Windows 10 Pro 10.0`
14 | 3. Demo script (if necessary) to reproduce your problem.
15 | 3. Distribute your question using this channels:
16 | 1. [Twitter #sqlhelp](https://twitter.com/search?q=%23sqlhelp&src=tyah) with `#sqlhelp` hash tag
17 | 2. [Slack #sqlhelp](https://sqlcommunity.slack.com/messages/sqlhelp/) (more than 700 People)
18 | 3. [SQLServerCentral Forum](https://www.sqlservercentral.com/Forums/)
19 | 4. Telegram chat (Russian preferred): https://t.me/sqlcom
20 |
--------------------------------------------------------------------------------
/PowerShell/Convert_trc_to_2008r2.ps1:
--------------------------------------------------------------------------------
1 | #requires -version 2.0
2 |
3 | <#
4 | .SYNOPSIS
5 | Changes the version information in the header of a SQL Server trace
6 |
7 | .DESCRIPTION
8 | Author: Gianluca Sartori - @spaghettidba
9 | Create date: 2012-11-07
10 | https://spaghettidba.com/2012/11/08/more-on-converting-trace-files/
11 |
12 | .PARAMETER fileName
13 | Trace file name
14 | #>
15 |
16 | ## =============================================
17 | ## Author: Gianluca Sartori - @spaghettidba
18 | ## Create date: 2012-11-07
19 | ## Description: Changes the version information
20 | ## in the header of a SQL Server trace
21 | ## =============================================
22 | $fileName = "somefile.trc"
23 |
24 | # The version information we want to write: 0x0A = 10 = SQLServer 2008
25 | [Byte[]] $versionData = 0x0A
26 | # The offset of the version information in the file
27 | $offset = 390
28 |
29 | [System.IO.FileMode] $open = [System.IO.FileMode]::OpenOrCreate
30 | $stream = New-Object System.IO.FileStream -ArgumentList $fileName, $open
31 | $stream.Seek($offset, [System.IO.SeekOrigin]::Begin);
32 | $stream.Write($versionData, 0, $versionData.Length);
33 | $stream.Close()
34 |
--------------------------------------------------------------------------------
/Stored_Procedure/dbo.usp_checkAllDatabases.sql:
--------------------------------------------------------------------------------
1 | /*
2 | Original link: http://stevestedman.com/2015/09/dbcc-checkdb-all-databases/
3 | Author: Steve Stedman
4 | */
5 |
6 | IF OBJECT_ID('dbo.usp_checkAllDatabases') IS NULL
7 | EXEC sp_executesql N'CREATE PROCEDURE dbo.usp_checkAllDatabases AS SELECT 1;'
8 | GO
9 |
10 | ALTER PROCEDURE usp_checkAllDatabases
11 | AS
12 | /*
13 | EXEC usp_checkAllDatabases;
14 | */
15 | BEGIN
16 | DECLARE @databaseList as CURSOR;
17 | DECLARE @databaseName as NVARCHAR(500);
18 | DECLARE @tsql AS NVARCHAR(500);
19 |
20 | SET @databaseList = CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY
21 | FOR
22 | SELECT QUOTENAME([name])
23 | FROM sys.databases
24 | WHERE [state] = 0
25 | AND [is_read_only] = 0;
26 | OPEN @databaseList;
27 | FETCH NEXT FROM @databaseList into @databaseName;
28 | WHILE @@FETCH_STATUS = 0
29 | BEGIN
30 | SET @tsql = N'DBCC CheckDB(' + @databaseName + ') WITH NO_INFOMSGS;';
31 | EXECUTE (@tsql);
32 | FETCH NEXT FROM @databaseList into @databaseName;
33 | END
34 | CLOSE @databaseList;
35 | DEALLOCATE @databaseList;
36 | END
37 | GO
38 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/Scripts/Create_2_Million_Tables.sql:
--------------------------------------------------------------------------------
1 | /*
2 | https://docs.microsoft.com/en-us/sql/sql-server/maximum-capacity-specifications-for-sql-server
3 | Database objects include objects such as tables, views, stored procedures, user-defined functions, triggers, rules, defaults, and constraints.
4 | The sum of the number of all objects in a database cannot exceed 2,147,483,647.
5 | */
6 | CREATE DATABASE [TwoMillion];
7 |
8 | ALTER DATABASE [TwoMillion] SET RECOVERY SIMPLE WITH NO_WAIT;
9 | GO
10 |
11 | USE [TwoMillion];
12 |
13 | SET NOCOUNT ON;
14 |
15 | DECLARE @sql nvarchar(max) = N'';
16 | DECLARE @i int = 1;
17 |
18 | SELECT @i = 2147483647 - COUNT(*) FROM [TwoMillion].sys.objects;
19 | PRINT N'Creating ' + FORMAT(@i,'N0') + N' tables...';
20 |
21 | WHILE @i > 0
22 | BEGIN
23 | SET @i -= 1;
24 |
25 | SET @sql = N'CREATE TABLE [TwoMillion].dbo.t' + CONVERT(nvarchar(max),2147483648-@i) + N' (i int);';
26 | IF (@i % 10000) = 0 RAISERROR(@sql, 0, 1) WITH NOWAIT;
27 |
28 | EXEC sp_executesql @sql;
29 | END;
30 |
31 | /*
32 | ALTER DATABASE [TwoMillion] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
33 | GO
34 |
35 | USE master;
36 | GO
37 |
38 | DROP DATABASE [TwoMillion];
39 | */
40 |
--------------------------------------------------------------------------------
/Scripts/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;
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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.**
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/Scripts/Generate_table_definition_to_match_query.sql:
--------------------------------------------------------------------------------
1 | /*
2 | Created: 2017-08-21 by SQL Undercover
3 | Modified: 2019-03-26 by Konstantin Taranov
4 | Original link: https://sqlundercover.com/2017/08/21/undercover-toolbox-generate-a-temporary-table-definition-to-match-the-resultset-of-a-query/
5 | Source link: https://github.com/ktaranov/sqlserver-kit/blob/master/Scripts/Generate_table_definition_to_match_query.sql
6 | */
7 |
8 | SET NOCOUNT ON;
9 |
10 | DECLARE @Query VARCHAR(MAX) = 'select * from sys.databases;';
11 | DECLARE @TempTableName VARCHAR(128) = '#temptable';
12 | DECLARE @ColumnList VARCHAR(MAX);
13 |
14 | SELECT @ColumnList = STUFF(
15 | (SELECT ' , ' + name + ' ' + system_type_name + ' ' +
16 | CASE is_nullable
17 | WHEN 0 THEN 'NOT NULL'
18 | ELSE 'NULL'
19 | END + CHAR(10)
20 | FROM sys.dm_exec_describe_first_result_set(@Query, NULL, 0)
21 | FOR XML PATH('')
22 | )
23 | ,1 ,1, '');
24 |
25 | PRINT 'CREATE TABLE ' + @TempTableName + '('
26 | PRINT @ColumnList;
27 | PRINT(');');
28 |
--------------------------------------------------------------------------------
/Scripts/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
--------------------------------------------------------------------------------
/PowerShell/Read_XEL_file.ps1:
--------------------------------------------------------------------------------
1 | $path = 'd:\system_health_0_131914905113690000.xel'
2 |
3 | #Add-Type -Path 'C:\Program Files (x86)\Microsoft SQL Server\120\Tools\Binn\ManagementStudio\Extensions\Application\Microsoft.SqlServer.XE.Core.dll'
4 | #Add-Type -Path 'C:\Program Files (x86)\Microsoft SQL Server\120\Tools\Binn\ManagementStudio\Extensions\Application\Microsoft.SqlServer.XEvent.Linq.dll'
5 |
6 | Add-Type -Path 'C:\Program Files\Microsoft SQL Server\120\Shared\Microsoft.SqlServer.XE.Core.dll'
7 | Add-Type -Path 'C:\Program Files\Microsoft SQL Server\120\Shared\Microsoft.SqlServer.XEvent.Linq.dll'
8 |
9 | $events = New-Object Microsoft.SqlServer.XEvent.Linq.QueryableXEventData($path)
10 | $sb = New-Object System.Text.StringBuilder
11 |
12 | $events | select -First 50 | %{
13 | $event = $_
14 | [void]$sb.Append("$($event.Timestamp);;");
15 |
16 | for($i=0;$i-lt($event.Fields.Count-1);$i++){
17 | [void]$sb.Append("$($event.Fields[$i].Value.ToString().Replace("`r`n", ''));;");
18 | }
19 |
20 | $event.Actions | %{
21 | $action = $_
22 | [void]$sb.Append("$($action.value.ToString().Replace("`r`n", ''));;");
23 | }
24 | [void]$sb.Append("ServerName;;");
25 |
26 | [void]$sb.AppendLine();
27 | }
28 | $sb.ToString();
29 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/Stored_Procedure/dbo.usp_RandomWait.sql:
--------------------------------------------------------------------------------
1 | ----------------------------------------------------------------------------------------------------------------
2 | --Procedure to wait randomized number of minutes or seconds, used to delay jobs
3 | ----------------------------------------------------------------------------------------------------------------
4 | IF OBJECT_ID('usp_RandomWait') IS NOT NULL DROP PROC usp_RandomWait
5 | GO
6 |
7 | CREATE PROC usp_RandomWait
8 | @sec_or_min char(1) = 'm'
9 | ,@span tinyint = 30
10 | AS
11 | IF @sec_or_min NOT IN ('s', 'm')
12 | BEGIN
13 | RAISERROR('The parameter @sec_or_min must be ''m'' (minutes) or ''s'' (seconds).', 16, 1)
14 | RETURN
15 | END
16 | DECLARE @towait char(2)
17 | ,@parsedWait char(8)
18 | ,@msg varchar(100)
19 | SET @towait = RIGHT('0' + CAST(CAST(RAND()*@span AS int)%@span+1 AS varchar(2)), 2)
20 | SET @parsedWait =
21 | CASE WHEN @sec_or_min = 's' THEN '00:00:' + @towait
22 | ELSE '00:' + @towait + ':00'
23 | END
24 | SET @msg = 'Waiting ' + @parsedWait
25 | RAISERROR (@msg, 10, 1) WITH NOWAIT
26 | WAITFOR DELAY @parsedWait
27 |
28 | /* Test
29 | EXEC usp_RandomWait
30 | EXEC usp_RandomWait @sec_or_min = 'm', @span = 30
31 | EXEC usp_RandomWait @sec_or_min = 's', @span = 10
32 | */
33 | GO
34 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/Scripts/Count_Database_Reads_and_Writes.sql:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | Counts reads and writes for databases
4 | Reads and writes per database.
5 | 2020-04-07 by Brent Ozar
6 | 2020-04-15 by Konstantin Taranov
7 | 1.1
8 | https://github.com/ktaranov/sqlserver-kit/blob/master/Scripts/Count_Database_Reads_and_Writes.sql
9 | https://www.brentozar.com/archive/2020/04/how-can-i-measure-if-my-database-does-more-reads-than-writes/
10 |
11 | */
12 |
13 |
14 | WITH reads_and_writes AS (
15 | SELECT db.name AS database_name,
16 | SUM(user_seeks + user_scans + user_lookups) AS reads,
17 | SUM(user_updates) AS writes,
18 | SUM(user_seeks + user_scans + user_lookups + user_updates) AS all_activity
19 | FROM sys.dm_db_index_usage_stats us
20 | INNER JOIN sys.databases db ON us.database_id = db.database_id
21 | GROUP BY db.name
22 | )
23 | SELECT
24 | database_name
25 | , reads
26 | , ((reads * 1.0) / all_activity) * 100 AS reads_percent
27 | , writes
28 | , ((writes * 1.0) / all_activity) * 100 AS writes_percent
29 | FROM reads_and_writes AS rw
30 | ORDER BY database_name;
31 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/Scripts/Reseed_Identity_Column_Value_To_Last_Value.sql:
--------------------------------------------------------------------------------
1 | /*
2 | https://eitanblumin.com/2018/11/06/re-align-identity-last-value-to-actual-max-value/
3 | */
4 |
5 | DECLARE @CurrTable SYSNAME, @CurrCol SYSNAME, @LastValue BIGINT
6 | DECLARE @CMD NVARCHAR(MAX), @Result NVARCHAR(MAX)
7 |
8 | DECLARE Cur CURSOR
9 | LOCAL FAST_FORWARD
10 | FOR
11 | SELECT QUOTENAME(OBJECT_SCHEMA_NAME(t.object_id)) + '.' + QUOTENAME(OBJECT_NAME(t.object_id)), c.name, CONVERT(int, c.last_value)
12 | FROM sys.identity_columns AS c
13 | INNER JOIN sys.tables AS t
14 | ON c.object_id = t.object_id
15 | WHERE c.last_value > c.seed_value
16 |
17 | OPEN Cur
18 | FETCH NEXT FROM Cur INTO @CurrTable, @CurrCol, @LastValue
19 |
20 | WHILE @@FETCH_STATUS = 0
21 | BEGIN
22 | SET @CMD = N'
23 | SELECT @pResult = N''DBCC CHECKIDENT(''''' + @CurrTable + N''''', RESEED, '' + CONVERT(nvarchar(max), MAX(' + QUOTENAME(@CurrCol) + N')) + N'') -- ' + CONVERT(nvarchar(max), @LastValue) + N'''
24 | FROM ' + @CurrTable + N'
25 | HAVING MAX(' + QUOTENAME(@CurrCol) + N') <> @LastValue'
26 |
27 | EXEC sp_executesql @CMD, N'@pResult NVARCHAR(MAX) OUTPUT, @LastValue BIGINT', @Result OUTPUT, @LastValue;
28 |
29 | IF @Result IS NOT NULL
30 | PRINT @Result;
31 |
32 | FETCH NEXT FROM Cur INTO @CurrTable, @CurrCol, @LastValue
33 | END
34 |
35 | CLOSE Cur
36 | DEALLOCATE Cur
--------------------------------------------------------------------------------
/Scripts/Using_OPENROWSET_to_Query_Excel.sql:
--------------------------------------------------------------------------------
1 | /*
2 | https://www.mssqltips.com/sqlservertip/6178/read-excel-file-in-sql-server-with-openrowset-or-opendatasource/
3 | */
4 |
5 | CREATE TABLE #Provider (
6 | ProviderName varchar(100) NOT NULL
7 | , [ParseName] varchar(100) NOT NULL
8 | , ProviderDescription varchar(100) NOT NULL
9 | );
10 |
11 | INSERT INTO #Provider EXEC sys.sp_enum_oledb_providers;
12 |
13 | IF NOT EXISTS (SELECT 1 FROM #Provider WHERE ProviderName LIKE 'Microsoft.ACE.OLEDB%')
14 | PRINT('Please install Microsoft.ACE.OLEDB driver: 16 - https://www.microsoft.com/en-us/download/details.aspx?id=54920 or 12 - https://www.microsoft.com/en-US/download/details.aspx?id=13255');
15 | ELSE PRINT('Microsoft.ACE.OLEDB is installed. Go next.');
16 |
17 | IF (SELECT "value" FROM sys.configurations WHERE "name" = 'Ad Hoc Distributed Queries') <> 1
18 | BEGIN
19 | EXEC sp_configure 'show advanced option', '1';
20 | RECONFIGURE;
21 | EXEC sp_configure 'Ad Hoc Distributed Queries', 1;
22 | RECONFIGURE;
23 | END;
24 |
25 | EXEC master.[sys].[sp_MSset_oledb_prop] N'Microsoft.ACE.OLEDB.16.0', N'AllowInProcess', 0;
26 |
27 | SELECT *
28 | FROM OPENROWSET(
29 | 'Microsoft.ACE.OLEDB.16.0'
30 | , 'Excel 12.0;Database=g:\MSSQL17\Instagram_Statistics.xlsx'
31 | , 'SELECT * FROM [decoupagpro$]') AS op;
32 |
--------------------------------------------------------------------------------
/Scripts/Get_Amazon_RDS_Instance_Size.sql:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | Get Amazon RDS Instance Size using TSQL
4 | 1 data set: InstanceSize.
5 | No
6 | Mitch Wheat
7 | 2008-07-27
8 | 2019-07-02 by Konstantin Taranov
9 | 1.0
10 | https://github.com/ktaranov/sqlserver-kit/blob/master/Scripts/Get_Amazon_RDS_Instance_Size.sql
11 | https://mitchwheat.com/2019/07/27/amazon-rds-sql-server-get-instance-size-using-tsql/
12 |
13 | */
14 |
15 | IF OBJECT_ID('tempdb..#AmazonErrorLog') IS NOT NULL
16 | DROP TABLE #AmazonErrorLog;
17 |
18 | CREATE TABLE #AmazonErrorLog
19 | (
20 | LogDate datetime2,
21 | ProcessInfo nvarchar(20),
22 | [Text] nvarchar(1000)
23 | );
24 |
25 | DECLARE @pattern nvarchar(30) = N'System Model:';
26 |
27 | INSERT INTO #AmazonErrorLog
28 | EXEC rdsadmin.dbo.rds_read_error_log;
29 |
30 | IF @@ROWCOUNT > 0
31 | BEGIN
32 | SELECT InstanceSize = REPLACE(CAST(SUBSTRING([Text], LEN(@pattern) + 1 + PATINDEX (N'%' + @pattern + N'%', [Text]), 100), '''', '') AS varchar(100))
33 | FROM #AmazonErrorLog
34 | WHERE PATINDEX (N'%' + @pattern + N'%', [Text]) > 0
35 | END;
36 |
37 | DROP TABLE #AmazonErrorLog;
38 |
--------------------------------------------------------------------------------
/Extended_Events/AppExecutionTimeout.sql:
--------------------------------------------------------------------------------
1 | /*
2 | Original link: http://blog.sqlgrease.com/how-to-detect-query-timeout-errors-with-extended-events/
3 | Author: Franklin Yamamoto
4 |
5 | SELECT
6 | object_name
7 | , convert(xml, event_data) AS event_data
8 | , file_name
9 | , file_offset
10 | FROM sys.fn_xe_file_target_read_file(N'AppExecutionTimeout*.xel',NULL,NULL,NULL);
11 | GO
12 | */
13 |
14 | /* Stop trace if started */
15 | IF EXISTS (SELECT * FROM sys.dm_xe_sessions WHERE name = 'AppExecutionTimeout')
16 | ALTER EVENT SESSION AppExecutionTimeout ON SERVER STATE = STOP;
17 |
18 | /* Delete trace if exists */
19 | IF EXISTS (SELECT * FROM sys.server_event_sessions WHERE name = 'AppExecutionTimeout')
20 | DROP EVENT SESSION AppExecutionTimeout ON SERVER;
21 |
22 | /* Create trace */
23 | CREATE EVENT SESSION AppExecutionTimeout ON SERVER
24 | ADD EVENT sqlserver.attention
25 | (ACTION (sqlserver.session_id, sqlserver.database_id, sqlserver.database_name,
26 | sqlserver.username, sqlserver.sql_text, sqlserver.client_hostname,
27 | sqlserver.client_app_name)
28 | WHERE ([package0].[equal_boolean]([sqlserver].[is_system],(0))))
29 | ADD TARGET package0.event_file(SET filename=N'AppExecutionTimeout.xel',
30 | max_file_size=(5),max_rollover_files=(2));
31 | GO
32 |
33 | ALTER EVENT SESSION AppExecutionTimeout ON SERVER STATE = START;
34 | GO
35 |
--------------------------------------------------------------------------------
/PowerShell/Read-XEL-File.ps1:
--------------------------------------------------------------------------------
1 | #requires -version 3.0
2 |
3 | <#
4 | .Synopsis
5 | Read Extended Event .xel file.
6 |
7 | .OUTPUTS
8 | First 50 rows of .xel file delimeted columns by ; and rows by \r\n
9 |
10 | .NOTES
11 | Original link: https://sqlserverpowershell.com/2017/04/06/read-an-extended-events-file-via-powershell/
12 | Author: Scott Newman
13 | #>
14 |
15 | $xelFilePath = 'c:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLSERVER\MSSQL\Log\system_health_0_131916022434590000.xel';
16 | $xelDDLPath = 'C:\Program Files\Microsoft SQL Server\140\Shared\';
17 |
18 | Add-Type -Path ($xelDDLPath+'Microsoft.SqlServer.XE.Core.dll');
19 | Add-Type -Path ($xelDDLPath+'Microsoft.SqlServer.XEvent.Linq.dll');
20 |
21 | $events = New-Object Microsoft.SqlServer.XEvent.Linq.QueryableXEventData($xelFilePath)
22 | $sb = New-Object System.Text.StringBuilder
23 |
24 | $events | select -First 50 | %{
25 | $event = $_
26 | [void]$sb.Append("$($event.Timestamp);;");
27 |
28 | for($i=0;$i-lt($event.Fields.Count-1);$i++){
29 | [void]$sb.Append("$($event.Fields[$i].Value.ToString().Replace("`r`n", ''));;");
30 | }
31 |
32 | $event.Actions | %{
33 | $action = $_
34 | [void]$sb.Append("$($action.value.ToString().Replace("`r`n", ''));;");
35 | }
36 | [void]$sb.Append("ServerName;;");
37 |
38 | [void]$sb.AppendLine();
39 | }
40 | $sb.ToString();
41 |
--------------------------------------------------------------------------------
/Scripts/Objects_Size_In_Database.sql:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | Count size in bytes veiws, triggers, procedures and function in database.
4 | 1 data set: RoutinType, SUM LENGTH of objects, SUM DATALENGTH.
5 | No
6 | Cade Roux
7 | 2008-10-20
8 | 2019-06-26 by Konstantin Taranov
9 | 1.0
10 | https://github.com/ktaranov/sqlserver-kit/blob/master/Scripts/Objects_Size_In_Database.sql
11 | https://stackoverflow.com/a/219740/2298061
12 |
13 | */
14 |
15 | SET NOCOUNT ON;
16 | SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
17 |
18 | WITH CTE_Routine AS (
19 | /* Can not use INFORMATION_SCHEMA.ROUTINES because of 4000 character limit */
20 | SELECT o.type_desc AS RoutineType
21 | , o.[name] AS RoutineName
22 | , m.[definition] AS RoutineDefinition
23 | FROM sys.sql_modules AS m
24 | INNER JOIN sys.objects AS o ON m.object_id = o.object_id
25 | )
26 | SELECT RoutineType
27 | , SUM(LEN(RoutineDefinition)) AS RoutineLen
28 | /* DATALENGTH for counting trailing space in the end of objects definitions */
29 | , SUM(DATALENGTH(RoutineDefinition)) / 2 AS RoutineDatalength
30 | FROM CTE_Routine
31 | GROUP BY RoutineType;
32 |
--------------------------------------------------------------------------------
/Scripts/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/Bad_Query_Example_13_JOINS.sql:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | Generate complex query plan
4 | Reads and writes per database.
5 | 2020-06-23 by Brent Ozar
6 | 2020-07-05 by Konstantin Taranov
7 | 1.1
8 | https://github.com/ktaranov/sqlserver-kit/blob/master/Scripts/Bad_Query_Example_13_JOINS.sql
9 | https://www.brentozar.com/archive/2020/06/bad-idea-jeans-building-big-query-plans/
10 |
11 | */
12 |
13 |
14 | DECLARE @TheRootOfAllEvil TABLE
15 | (Id int PRIMARY KEY CLUSTERED);
16 | WITH CTE1 AS (SELECT * FROM @TheRootOfAllEvil r1),
17 | CTE2 AS (SELECT cA.* FROM CTE1 cA INNER JOIN CTE1 cB ON cA.Id = cB.Id),
18 | CTE3 AS (SELECT cA.* FROM CTE2 cA INNER JOIN CTE2 cB ON cA.Id = cB.Id),
19 | CTE4 AS (SELECT cA.* FROM CTE3 cA INNER JOIN CTE3 cB ON cA.Id = cB.Id),
20 | CTE5 AS (SELECT cA.* FROM CTE4 cA INNER JOIN CTE4 cB ON cA.Id = cB.Id),
21 | CTE6 AS (SELECT cA.* FROM CTE5 cA INNER JOIN CTE5 cB ON cA.Id = cB.Id),
22 | CTE7 AS (SELECT cA.* FROM CTE6 cA INNER JOIN CTE6 cB ON cA.Id = cB.Id),
23 | CTE8 AS (SELECT cA.* FROM CTE7 cA INNER JOIN CTE7 cB ON cA.Id = cB.Id),
24 | CTE9 AS (SELECT cA.* FROM CTE8 cA INNER JOIN CTE8 cB ON cA.Id = cB.Id),
25 | CTE10 AS (SELECT cA.* FROM CTE9 cA INNER JOIN CTE9 cB ON cA.Id = cB.Id)
26 | SELECT * FROM CTE10;
27 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 | ;
--------------------------------------------------------------------------------
/Scripts/SQL_Azure_Approximate_Datetime_Restart.sql:
--------------------------------------------------------------------------------
1 | /*
2 | Author: Mitch Wheat
3 | Original link: https://mitchwheat.com/2018/10/12/when-did-my-azure-sql-database-server-restart/
4 | Created Date: 2018-10-18
5 | Modified Date: 2018-10-18
6 | */
7 |
8 | ;with cte as
9 | (
10 | SELECT wait_time_ms
11 | FROM sys.dm_os_wait_stats w with(nolock)
12 | WHERE wait_type IN
13 | (
14 | 'BROKER_TASK_STOP',
15 | 'DIRTY_PAGE_POLL',
16 | 'HADR_FILESTREAM_IOMGR_IOCOMPLETION',
17 | 'LAZYWRITER_SLEEP',
18 | 'LOGMGR_QUEUE',
19 | 'REQUEST_FOR_DEADLOCK_SEARCH',
20 | 'XE_DISPATCHER_WAIT',
21 | 'XE_TIMER_EVENT'
22 | )
23 | )
24 | select
25 | approx_ms_since_restart = AVG(wait_time_ms),
26 | approximate_restart_date = DATEADD(s, AVG(-wait_time_ms)/1000, GETDATE())
27 | from
28 | cte
29 | cross join
30 | (select
31 | q1 = min(wait_time_ms),
32 | q3 = max(wait_time_ms),
33 | iqr = max(wait_time_ms) - min(wait_time_ms)
34 | from (select
35 | wait_time_ms,
36 | row_number() over (order by wait_time_ms) as seqnum,
37 | count(*) over (partition by null) as total
38 | from cte
39 | ) t
40 | where seqnum = cast(total * 0.25 as int) or seqnum = cast(total * 0.75 as int)
41 | ) qts
42 | where (wait_time_ms >= q1 - 1.5 * iqr) AND (wait_time_ms <= q3 + 1.5 * iqr);
43 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/Extended_Events/QueryExecutionDetails.sql:
--------------------------------------------------------------------------------
1 | /*
2 | Original link: https://www.scarydba.com/2019/06/03/which-query-used-the-most-cpu-implementing-extended-events/
3 | Source link: https://github.com/ktaranov/sqlserver-kit/blob/master/Extended_Events/DBRecoveryProgress.sql
4 | Author: Grant Fritchey
5 | */
6 |
7 | USE master;
8 | GO
9 |
10 | IF EXISTS
11 | (
12 | SELECT
13 | *
14 | FROM sys.server_event_sessions
15 | WHERE name = 'QueryExecutionDetails'
16 | )
17 | DROP EVENT SESSION QueryExecutionDetails ON SERVER;
18 | GO
19 |
20 | CREATE EVENT SESSION QueryExecutionDetails
21 | ON SERVER
22 | ADD EVENT sqlserver.rpc_completed
23 | (WHERE (sqlserver.database_name = N'AdventureWorks')),
24 | ADD EVENT sqlserver.rpc_starting
25 | (WHERE (sqlserver.database_name = N'AdventureWorks')),
26 | ADD EVENT sqlserver.sp_statement_completed
27 | (WHERE (sqlserver.database_name = N'AdventureWorks')),
28 | ADD EVENT sqlserver.sql_batch_completed
29 | (WHERE (sqlserver.database_name = N'AdventureWorks')),
30 | ADD EVENT sqlserver.sql_batch_starting
31 | (WHERE (sqlserver.database_name = N'AdventureWorks')),
32 | ADD EVENT sqlserver.sql_statement_completed
33 | (SET collect_statement = (1)
34 | WHERE (sqlserver.database_name = N'AdventureWorks'))
35 | ADD TARGET package0.event_file
36 | (SET filename = N'C:\ExEvents\QueryExecutionDetails.xel')
37 | WITH (TRACK_CAUSALITY = ON);
38 |
39 | ALTER EVENT SESSION QueryExecutionDetails ON SERVER STATE = START;
40 | GO
41 |
--------------------------------------------------------------------------------
/Scripts/Job_AG_Failover_Detected.sql:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | Use this event to run a job when the replica becomes primary
4 | Create job to resume AG database data movement for suspended databases.
5 | 2020-08-06 by Wayne Sheffield
6 | 1.0
7 | https://github.com/ktaranov/sqlserver-kit/blob/master/Scripts/Job_AG_Failover_Detected.sql
8 | https://blog.waynesheffield.com/wayne/archive/2020/08/availability-group-issues-fixed-with-alerts/
9 |
10 | */
11 |
12 | /*
13 | Use this event to run a job when the replica becomes primary
14 | */
15 | USE msdb;
16 | GO
17 | EXEC msdb.dbo.sp_add_alert @name=N'AG Failover Detected - Now Primary',
18 | @message_id=1480,
19 | @severity=0,
20 | @enabled=1,
21 | @delay_between_responses=0,
22 | @include_event_description_in=0,
23 | @event_description_keyword=N'"RESOLVING" to "PRIMARY"',
24 | @job_id=N'00000000-0000-0000-0000-000000000000';
25 | GO
26 | /*
27 | Use this event to run a job when the replica becomes secondary
28 | */
29 | USE msdb;
30 | GO
31 | EXEC msdb.dbo.sp_add_alert @name=N'AG Failover Detected - Now Secondary',
32 | @message_id=1480,
33 | @severity=0,
34 | @enabled=1,
35 | @delay_between_responses=0,
36 | @include_event_description_in=0,
37 | @event_description_keyword=N'"RESOLVING" to "SECONDARY"',
38 | @job_id=N'00000000-0000-0000-0000-000000000000';
39 | GO
40 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/CLR/README.md:
--------------------------------------------------------------------------------
1 | # Microsoft SQL Server CLR
2 |
3 | Useful links:
4 | - [Introduction to SQL Server CLR Integration](https://msdn.microsoft.com/en-us/library/ms254498(v=vs.110).aspx)
5 | - [CLR User-Defined Functions](https://msdn.microsoft.com/library/ms131077.aspx)
6 | - [CLR User-Defined Types](https://msdn.microsoft.com/en-us/library/ms131120(SQL.100).aspx)
7 | - [CLR Stored Procedures](https://msdn.microsoft.com/en-us/library/ms131094(SQL.100).aspx)
8 | - [CLR Triggers](https://msdn.microsoft.com/en-us/library/ms131093(SQL.100).aspx)
9 | - [SQL# CLR functions](https://SQLsharp.com/) (by Sql Quantum Lift)
10 |
11 | The common language runtime (CLR) is the heart of the Microsoft .NET Framework and provides the execution environment for all .NET Framework code. Code that runs within the CLR is referred to as managed code. The CLR provides various functions and services required for program execution, including just-in-time (JIT) compilation, allocating and managing memory, enforcing type safety, exception handling, thread management, and security.
12 |
13 | With the CLR hosted in Microsoft SQL Server (called CLR integration), you can author stored procedures, triggers, user-defined functions, user-defined types, and user-defined aggregates in managed code. Because managed code compiles to native code prior to execution, you can achieve significant performance increases in some scenarios.
14 |
15 | Enabling CLR Integration:
16 |
17 | ```tsql
18 | EXEC sp_configure 'clr enabled', 1;
19 | RECONFIGURE;
20 | GO
21 | ```
22 |
--------------------------------------------------------------------------------
/Errors/PDB/README.md:
--------------------------------------------------------------------------------
1 | # SQL Server Debugging
2 |
3 | - [Obtaining symbol files (.PDB) for SQL Server Releases](https://github.com/arvindshmicrosoft/SQLCallStackResolver/wiki/Scripts-to-download-symbols-for-SQL-Server-2019)
4 | - [What is the SOS_WORK_DISPATCHER Wait Type?](https://orderbyselectnull.com/2018/09/27/what-is-the-sos_work_dispatcher-wait-type/)
5 | - [An XEvent a Day (24 of 31) – What is the callstack?](https://www.sqlskills.com/blogs/jonathan/an-xevent-a-day-24-of-31-what-is-the-callstack/)
6 |
7 | This section contains PowerShell scripts which automate the download and extraction of `.PDB` files corresponding to major releases of SQL Server.
8 |
9 | For running any of these scripts, please note the following:
10 | - You must run them within PowerShell, preferably within Windows
11 | - You must have Internet access from the machine running the PowerShell script
12 | - You might want to replace the $outputFolder placeholder with a different folder path (for example, `N:\sqlsymbols\SQL2016SP1`)
13 | - The script will automatically create the folder where the downloaded PDB files are stored.
14 |
15 | Please click on one of the links below depending on the major version of SQL Server that you are looking at:
16 | - [SQL Server 2019](SQL-Server-2019.md)
17 | - [SQL Server 2017](SQL-Server-2017.md)
18 | - [SQL Server 2016](SQL-Server-2016.md)
19 | - [SQL Server 2014](SQL-Server-2014.md)
20 | - [SQL Server 2012](SQL-Server-2012.md)
21 | - [SQL Server 2008 R2](SQL-Server-2008-R2.md)
22 | - [SQL Server 2008](SQL-Server-2008.md)
23 |
--------------------------------------------------------------------------------
/Extended_Events/ADS_Standard_Azure.sql:
--------------------------------------------------------------------------------
1 | /*
2 | Original link: https://sqlperformance.com/2020/04/sql-performance/bandwidth-friendly-query-profiling-azure-sql-database
3 | Author: Greg Gonzalez
4 | */
5 |
6 | ALTER EVENT SESSION [ADS_Standard_Azure] ON DATABASE
7 | DROP EVENT sqlserver.attention,
8 | DROP EVENT sqlserver.existing_connection,
9 | DROP EVENT sqlserver.login,
10 | DROP EVENT sqlserver.logout,
11 | DROP EVENT sqlserver.rpc_completed,
12 | DROP EVENT sqlserver.sql_batch_completed,
13 | DROP EVENT sqlserver.sql_batch_starting
14 | GO
15 |
16 | ALTER EVENT SESSION [ADS_Standard_Azure] ON DATABASE
17 | ADD EVENT sqlserver.rpc_completed(
18 | ACTION(package0.event_sequence,sqlserver.client_app_name,sqlserver.client_pid,sqlserver.database_id,sqlserver.query_hash,sqlserver.session_id,sqlserver.username)
19 | WHERE (([package0].[equal_boolean]([sqlserver].[is_system],(0))) AND ([duration] >= (1000000)))),
20 | ADD EVENT sqlserver.sql_batch_completed(
21 | ACTION(package0.event_sequence,sqlserver.client_app_name,sqlserver.client_pid,sqlserver.database_id,sqlserver.query_hash,sqlserver.session_id,sqlserver.username)
22 | WHERE (([package0].[equal_boolean]([sqlserver].[is_system],(0))) AND ([duration] >= (1000000))))
23 | GO
24 |
25 | ALTER EVENT SESSION [ADS_Standard_Azure] ON DATABASE
26 | DROP TARGET package0.ring_buffer
27 | GO
28 |
29 | ALTER EVENT SESSION [ADS_Standard_Azure] ON DATABASE
30 | ADD TARGET package0.ring_buffer(SET max_events_limit=(10),max_memory=(51200))
31 | GO
32 |
--------------------------------------------------------------------------------
/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/Find_Maximum_Float_Values.sql:
--------------------------------------------------------------------------------
1 | /*
2 | https://docs.microsoft.com/en-us/sql/t-sql/data-types/float-and-real-transact-sql
3 | */
4 |
5 | SELECT CAST(-2.22999999999999E-308 AS float(53)) AS "Float(53) Negative Max"
6 | , CAST(-1.797693134862315807E+308 AS float(53)) AS "Float(53) Negative Min"
7 | , CAST(+1.797693134862315807E+308 AS float(53)) AS "Float(53) Positive Max";
8 |
9 |
10 | SET NOCOUNT ON;
11 |
12 | DROP TABLE IF EXISTS t;
13 | CREATE TABLE t (
14 | i int IDENTITY(1, 1) NOT NULL
15 | , f float(53) NOT NULL
16 | , s varchar(100) NOT NULL
17 | );
18 | GO
19 |
20 | DECLARE @s varchar(100) = '+1.79'; /* +1.79 -2.22*/
21 | DECLARE @i int = 1;
22 | DECLARE @j int = 9;
23 |
24 | WHILE (@i < 200 AND LEN(@s) < 22)
25 | BEGIN
26 | BEGIN TRY
27 | SET @i = @i + 1;
28 |
29 | INSERT INTO t(f, s) SELECT CAST((@s + CAST(@j AS varchar) + 'E' + LEFT(@s, 1) + '308') AS float(53)), @s AS s;
30 | SET @s = (@s + CAST(@j AS varchar));
31 | SET @j = 9;
32 | END TRY
33 |
34 | BEGIN CATCH
35 | SELECT ERROR_NUMBER() AS ErrorNumber
36 | ,ERROR_SEVERITY() AS ErrorSeverity
37 | ,ERROR_STATE() AS ErrorState
38 | ,ERROR_PROCEDURE() AS ErrorProcedure
39 | ,ERROR_LINE() AS ErrorLine
40 | ,ERROR_MESSAGE() AS ErrorMessage;
41 | SET @j = @j - 1;
42 | END CATCH
43 | END;
44 |
45 | SELECT i, f, s
46 | FROM t
47 | WHERE f = (SELECT MAX(f) AS FLOAT_MAX FROM t);
48 |
--------------------------------------------------------------------------------
/PowerShell/ParameterCaseCheck.ps1:
--------------------------------------------------------------------------------
1 | <#
2 | .Synopsis
3 | Search for any parameter that does not match the column name.
4 |
5 | .OUTPUTS
6 | Any parameter that does not match the column name
7 |
8 | .NOTES
9 | Original link: https://nocolumnname.blog/2018/05/25/finding-parameters-that-do-not-match-column-names/
10 | Author: Shane O'Neill
11 | #>
12 |
13 | $PatternMatch = '(?\w+)\s*=\s*@(?\w+)'
14 |
15 | $FindStoredProcedureParameters = @{
16 | SqlInstance = 'localhost'
17 | Database = 'master'
18 | Pattern = $PatternMatch
19 | IncludeSystemDatabases = $true
20 | }
21 |
22 | Find-DbaStoredProcedure @FindStoredProcedureParameters |
23 | ForEach-Object -Process {
24 | $ParentRow = $_
25 |
26 | $_ | ForEach-Object StoredProcedureTextFound | Select-String -Pattern $PatternMatch -AllMatches | ForEach-Object Matches | ForEach-Object -Process {
27 | [PSCustomObject]@{
28 | ServerName = $ParentRow.SqlInstance
29 | DatabaseName = $ParentRow.Database
30 | SchemaName = $ParentRow.Schema
31 | ProcedureName = $ParentRow.Name
32 | TextFound = ($_.Groups | Where-Object Name -eq '0').Value
33 | ColumnName = ($_.Groups | Where-Object Name -eq 'ColumnName').Value
34 | ParameterName = ($_.Groups | Where-Object Name -eq 'ParameterName').Value
35 | }
36 | }
37 | } | Where-Object { ($_.ColumnName -ne $_.ParameterName) } |
38 | Select-Object -Property * -Unique
39 |
--------------------------------------------------------------------------------
/Scripts/Failed_SQL_Server_Agent_Jobs_With_Restart_Command.sql:
--------------------------------------------------------------------------------
1 | /*
2 | Author: Max Vernon
3 | Created Date: 2019-02-05
4 | Original link: https://blog.sqlauthority.com/2018/09/12/sql-server-simple-method-to-extract-scale-part-from-decimal-number/
5 | Source link: https://github.com/ktaranov/sqlserver-kit/blob/master/Scripts/Failed_SQL_Server_Agent_Jobs_With_Restart_Command.sql
6 | Modified: 2019-02-11 by Konstantin Taranov
7 | */
8 |
9 | WITH sys_job_history AS
10 | (
11 | SELECT *
12 | , rn = ROW_NUMBER() OVER (PARTITION BY sjh.job_id ORDER BY msdb.dbo.agent_datetime(sjh.run_date, sjh.run_time) DESC)
13 | FROM msdb.dbo.sysjobhistory sjh
14 | WHERE sjh.step_id > 0
15 | AND sjh.run_date > CONVERT(int, CONVERT(varchar(8), DATEADD(DAY, -1, GETDATE()), 112))
16 | )
17 | SELECT sj.name
18 | , sjh.step_name
19 | , sjh.step_id
20 | , sjh.sql_message_id
21 | , sjh.sql_severity
22 | , sjh.message
23 | , sjh.server
24 | , RunDateTime = msdb.dbo.agent_datetime(sjh.run_date, sjh.run_time)
25 | , StartJobCommand = N'EXEC msdb.dbo.sp_start_job @job_name = ''' + sj.name + N''', @step_name = ''' + sjh.step_name + N''';'
26 | FROM sys_job_history sjh
27 | INNER JOIN msdb.dbo.sysjobs sj ON sjh.job_id = sj.job_id
28 | INNER JOIN msdb.dbo.sysjobschedules sjsch ON sj.job_id = sjsch.job_id
29 | INNER JOIN msdb.dbo.sysschedules ss ON sjsch.schedule_id = ss.schedule_id
30 | WHERE sjh.rn = 1
31 | AND sjh.run_status = 0 --failed
32 | AND ss.enabled = 1
33 | ORDER BY sj.name;
34 |
--------------------------------------------------------------------------------
/Scripts/Get_CPU_Usage_Per_Database.sql:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | Get CPU Usage Per Database
4 | 1 data set with 2 columns: database name and CPUTimeAsPercentage.
5 | No
6 | Eli Leiba
7 | 2019-11-05
8 | 2019-11-05
9 | 1.0
10 | https://www.mssqltips.com/sqlservertip/6195/sql-server-function-to-measure-cpu-usage-per-database/
11 | https://github.com/ktaranov/sqlserver-kit/blob/master/Scripts/Get_CPU_Usage_Per_Database.sql
12 |
13 | */
14 |
15 | SELECT
16 | T.[Database]
17 | , T.CPUTimeAsPercentage
18 | FROM
19 | (SELECT
20 | [Database],
21 | CONVERT (DECIMAL (6, 3), [CPUTimeInMiliSeconds] * 1.0 /
22 | SUM ([CPUTimeInMiliSeconds]) OVER () * 100.0) AS [CPUTimeAsPercentage]
23 | FROM
24 | (SELECT
25 | dm_execplanattr.DatabaseID,
26 | DB_Name(dm_execplanattr.DatabaseID) AS [Database],
27 | SUM (dm_execquerystats.total_worker_time) AS CPUTimeInMiliSeconds
28 | FROM sys.dm_exec_query_stats dm_execquerystats
29 | CROSS APPLY
30 | (SELECT
31 | CONVERT (INT, value) AS [DatabaseID]
32 | FROM sys.dm_exec_plan_attributes(dm_execquerystats.plan_handle)
33 | WHERE attribute = N'dbid'
34 | ) dm_execplanattr
35 | GROUP BY dm_execplanattr.DatabaseID
36 | ) AS CPUPerDb
37 | ) AS T;
38 |
--------------------------------------------------------------------------------
/Scripts/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/Foreign_Keys_With_No_Index.sql:
--------------------------------------------------------------------------------
1 | /*
2 | Author: Drupal
3 | Original link: http://sqlworldwide.com/tsql-to-find-status-of-sql-server-statistics/
4 | */
5 |
6 |
7 | WITH fk_cte AS (
8 | SELECT OBJECT_NAME(fk.referenced_object_id) pk_table
9 | , c2.name pk_column
10 | , kc.name pk_index_name
11 | , OBJECT_NAME(fk.parent_object_id) fk_table
12 | , c.name fk_column
13 | , fk.name fk_name
14 | , CASE WHEN i.object_id IS NOT NULL THEN 1 ELSE 0 END does_fk_has_index
15 | , i.is_primary_key is_fk_a_pk_also
16 | , i.is_unique is_index_on_fk_unique
17 | , fk.*
18 | FROM sys.foreign_keys AS fk
19 | INNER JOIN sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id
20 | INNER JOIN sys.columns AS c ON c.object_id = fk.parent_object_id AND c.column_id = fkc.parent_column_id
21 | LEFT JOIN sys.columns AS c2 ON c2.object_id = fk.referenced_object_id AND c2.column_id = fkc.referenced_column_id
22 | LEFT JOIN sys.key_constraints AS kc ON kc.parent_object_id = fk.referenced_object_id AND kc.type = 'PK'
23 | LEFT JOIN sys.index_columns AS ic ON ic.object_id = c.object_id AND ic.column_id = c.column_id
24 | LEFT JOIN sys.indexes AS i ON i.object_id = ic.object_id AND i.index_id = ic.index_id
25 | )
26 | SELECT * FROM fk_cte
27 | LEFT JOIN sys.dm_db_partition_stats ps on ps.object_id = fk_cte.parent_object_id and ps.index_id <= 1
28 | WHERE does_fk_has_index = 0 -- and fk_table = 'LineItems'
29 | ORDER BY used_page_count DESC;
30 |
--------------------------------------------------------------------------------
/Scripts/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/Scripts/Numbers_DATALENGTH.sql:
--------------------------------------------------------------------------------
1 | SELECT DATALENGTH(CAST(99999999999999999999999999999999999999 AS decimal(38, 0))) AS DECIMAL38
2 | , DATALENGTH(CAST( 9999999999999999999999999999 AS decimal(28, 0))) AS DECIMAL28
3 | , DATALENGTH(CAST( 9999999999999999999 AS decimal(19, 0))) AS DECIMAL19
4 | , DATALENGTH(CAST( 999999999 AS decimal( 9, 0))) AS DECIMAL9
5 | , DATALENGTH(CAST( 9 AS decimal( 1, 0))) AS DECIMAL1
6 | , DATALENGTH(CAST( 1.797693134862315807E+308 AS float(53))) AS FLOAT53
7 | , DATALENGTH(CAST( 9999999999999999999999999 AS float(25))) AS FLOAT25
8 | , DATALENGTH(CAST( 999999999999999999999999 AS float(24))) AS FLOAT24
9 | , DATALENGTH(CAST( 9 AS float( 1))) AS FLOAT1
10 | , DATALENGTH(CAST( 999999999999999999999999 AS real)) AS "REAL"
11 | , DATALENGTH(CAST( 9223372036854775807 AS bigint )) AS "BIGINT"
12 | , DATALENGTH(CAST( 2147483647 AS int )) AS "INT"
13 | , DATALENGTH(CAST( 32600 AS smallint )) AS "SMALLINT"
14 | , DATALENGTH(CAST( 255 AS tinyint )) AS "TINYINT"
15 | , DATALENGTH(CAST( 0 AS bit )) AS BIT0
16 | , DATALENGTH(CAST( 1.797693134862315807E+308 AS bit )) AS BIT1
17 | , DATALENGTH(POWER(10.0, 37)) AS "Power10^37";
18 |
--------------------------------------------------------------------------------
/Scripts/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 |
--------------------------------------------------------------------------------
/Stored_Procedure/dbo.usp_PrintDebug.sql:
--------------------------------------------------------------------------------
1 | IF OBJECT_ID('dbo.usp_PrintDebug', 'P') IS NULL
2 | EXECUTE('CREATE PROCEDURE dbo.usp_PrintDebug AS SELECT 1') ;
3 | GO
4 |
5 |
6 | ALTER PROCEDURE dbo.usp_PrintDebug
7 | (
8 | @variableName NVARCHAR(MAX) = '',
9 | @variableValue NVARCHAR(MAX) = '',
10 | @printMessage NVARCHAR(MAX) = ''
11 | )
12 | /*
13 | EXECUTE dbo.usp_PrintDebug @variableName = 'maxDate', @variableValue = ''
14 | EXECUTE dbo.usp_PrintDebug @printMessage = 'start_debug'
15 | EXECUTE dbo.usp_PrintDebug @printMessage = 'end_debug'
16 | EXECUTE dbo.usp_PrintDebug @printMessage = 'Test debug'
17 | */
18 | AS
19 | BEGIN
20 | DECLARE @Crlf NVARCHAR(10) = CHAR(13) ;
21 | BEGIN TRY
22 | IF @printMessage = ''
23 | IF @variableValue IS NOT NULL AND CAST(@variableValue AS NVARCHAR) != ''
24 | PRINT '@' + @variableName + ' = {' + CAST(@variableValue AS NVARCHAR) + '}'
25 | ELSE
26 | IF CAST(@variableValue AS NVARCHAR) = ''
27 | PRINT @variableName + ' = {Empty String}'
28 | ELSE
29 | IF @variableValue IS NULL
30 | PRINT @variableName + ' = {NULL}';
31 |
32 | IF @printMessage LIKE 'start_debug %'
33 | PRINT '/******* Start Debug' + REPLACE(@printMessage, 'start_debug' , ' ') + @Crlf;
34 |
35 | IF @printMessage LIKE 'end_debug %'
36 | PRINT @Crlf + '--End Deubg ' + REPLACE(@printMessage, 'end_debug' , '') + ' *********/';
37 |
38 | IF @printMessage NOT LIKE '%_debug%'
39 | PRINT @printMessage;
40 | END TRY
41 |
42 | BEGIN CATCH
43 | EXECUTE usp_LogError;
44 | END CATCH
45 | END;
46 | go
47 |
--------------------------------------------------------------------------------
/Stored_Procedure/dbo.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 |
--------------------------------------------------------------------------------
/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/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/Who_dropped_altered_database_object.sql:
--------------------------------------------------------------------------------
1 | /*
2 | Created: 2018-10-31 by Rebecca Lewis
3 | Modified: 2019-03-26 by Konstantin Taranov
4 | Original link: http://www.sqlfingers.com/2018/10/who-dropped-that-table.html
5 | Source link: https://github.com/ktaranov/sqlserver-kit/blob/master/Scripts/Who_dropped_altered_database_object.sql
6 | */
7 |
8 | SET NOCOUNT ON;
9 |
10 | DECLARE @current NVARCHAR(255);
11 | DECLARE @start NVARCHAR(255);
12 | DECLARE @index INT;
13 |
14 | /* find your trace path */
15 | SELECT @current = path FROM sys.traces WHERE is_default = 1;
16 |
17 | SET @current = REVERSE(@current);
18 | SET @index = PATINDEX('%\%', @current);
19 | SET @current = REVERSE(@current);
20 | SET @start = LEFT(@current, LEN(@current) - @index) + N'\log.trc';
21 |
22 | /* query on the eventclasses for delete and alter */
23 | SELECT te.name AS EventName
24 | , gt.DatabaseName
25 | , gt.ObjectName
26 | , gt.StartTime
27 | , gt.EndTime
28 | , gt.HostName
29 | , gt.ApplicationName
30 | , gt.NTUserName
31 | , gt.NTDomainName
32 | , gt.LoginName
33 | , gt.SPID
34 | , gt.EventClass
35 | , gt.EventSubClass
36 | , gt.TextData
37 | , gt.FileName
38 | , gt.IsSystem
39 | FROM fn_trace_gettable(@start, DEFAULT) AS gt
40 | LEFT JOIN sys.trace_events AS te ON gt.EventClass = te.trace_event_id
41 | WHERE gt.EventSubClass = 0
42 | AND gt.DatabaseID <> 2 /* tempdb */
43 | /*
44 | AND EventClass IN ( 164 /* Object:Deleted */
45 | , 47 /* Object:Altered */
46 | , 46 /* Object:Created */
47 | )
48 | */
49 | ORDER BY gt.StartTime;
50 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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/Export_Query_To_Csv.ps1:
--------------------------------------------------------------------------------
1 | #requires -version 5.0
2 | #requires -modules sqlserver
3 |
4 | <#
5 | .SYNOPSIS
6 | Export SQL server table to csv file with quotes (if needed) and header
7 |
8 | .DESCRIPTION
9 | Piping Invoke-Sqlcmd into csv file with quotes only if needed.
10 | Also replace False and True on 0 and 1 for bit types columns.
11 |
12 | .NOTES
13 | Original link: http://www.sqlmovers.com/removing-quotes-from-csv-created-by-powershell/
14 | Author: Russ Loski
15 | Version: 1.3
16 | Modified: 2020-01-09 by Konstantin Taranov
17 | Source link: https://github.com/ktaranov/sqlserver-kit/blob/master/Powershell/Export_Query_To_Csv.ps1
18 | #>
19 |
20 | $databaseName = "master";
21 | $fileName = $tableName = "sys.objects";
22 | $delimiter = ","; # possible values "`t", ",", ";", "|"
23 | if ($delimiter -eq "|") {
24 | $delimiterReg = $delimiterBit = "\|";
25 | } else {
26 | $delimiterReg = $delimiterBit = $delimiter;
27 | };
28 | $regReplace = '\G(?^|' + $delimiterReg + '+)(("(?