Tuesday, 26 August 2025

SQLDBA- Deadlock graph query

 


Dead lock graph query

DECLARE @xelfilepath NVARCHAR(260)

SELECT @xelfilepath = dosdlc.path

FROM sys.dm_os_server_diagnostics_log_configurations AS dosdlc;

SELECT @xelfilepath = @xelfilepath + N'system_health_*.xel'

 DROP TABLE IF EXISTS  #TempTable

 SELECT CONVERT(XML, event_data) AS EventData

        INTO #TempTable FROM sys.fn_xe_file_target_read_file(@xelfilepath, NULL, NULL, NULL)

         WHERE object_name = 'xml_deadlock_report'

SELECT EventData.value('(event/@timestamp)[1]', 'datetime2(7)') AS UtcTime, 

            CONVERT(DATETIME, SWITCHOFFSET(CONVERT(DATETIMEOFFSET, 

      EventData.value('(event/@timestamp)[1]', 'VARCHAR(50)')), DATENAME(TzOffset, SYSDATETIMEOFFSET()))) AS LocalTime, 

            EventData.query('event/data/value/deadlock') AS XmlDeadlockReport

     FROM #TempTable

     ORDER BY UtcTime DESC;

Monday, 18 August 2025

SQLDBA - ADM - Long Running Jobs

 



  

  

  

CREATE PROC [dbo].[sp_longrunningjobs]   

(  

 @hours INT  

)  

  

AS  

/***********************************************************    

DESCRIPTION:   

Shows all SQLAgent jobs that have been running longer than the amount of hours specified in  

the parameter. 

  

************************************************************/  

  

DECLARE @report_query VARCHAR(8000);  

DECLARE @string VARCHAR(100);  

DECLARE @xml NVARCHAR(MAX);  

DECLARE @body NVARCHAR(MAX);  

DECLARE @currently_running_jobs TABLE (  

 job_id UNIQUEIDENTIFIER NOT NULL  

 ,last_run_date INT NOT NULL  

 ,last_run_time INT NOT NULL  

 ,next_run_date INT NOT NULL  

 ,next_run_time INT NOT NULL  

 ,next_run_schedule_id INT NOT NULL  

 ,requested_to_run INT NOT NULL  

 ,-- BOOL  

 request_source INT NOT NULL  

 ,request_source_id SYSNAME COLLATE database_default NULL  

 ,running INT NOT NULL  

 ,-- BOOL  

 current_step INT NOT NULL  

 ,current_retry_attempt INT NOT NULL  

 ,job_state INT NOT NULL  

 )  

  

--Capture Jobs currently working  

INSERT INTO @currently_running_jobs  

EXECUTE master.dbo.xp_sqlagent_enum_jobs 1  

 ,''  

  

SET @string = 'Long Running SQLAgent Jobs on ' + @@servername  

SET @xml = CAST((  

   SELECT DISTINCT jobs.[name] AS 'td'  

    ,''  

    ,ja.run_requested_date AS 'td'  

    ,''  

    ,DATEDIFF(hour, ja.run_requested_date, getdate()) AS 'td'  

   FROM @currently_running_jobs AS crj  

   INNER JOIN msdb..sysjobs AS jobs ON crj.job_id = jobs.job_id  

   INNER JOIN msdb..sysjobactivity AS ja ON ja.job_id = crj.job_id  

   WHERE crj.running = 1  

    AND ja.run_requested_date = (  

     SELECT max(ja1.run_requested_date)  

     FROM msdb..sysjobactivity AS ja1  

     WHERE ja1.job_id = crj.job_id  

     )  

    AND DATEDIFF(hour, ja.run_requested_date, getdate()) >= 5--@hours

    AND jobs.[name] NOT LIKE ('%Database Consistency%')  

   ORDER BY jobs.[name] DESC  

   FOR XML PATH('tr')  

    ,ELEMENTS  

   ) AS NVARCHAR(MAX))  

SET @body = '<html><body><H3>The following jobs have been running for more than 5 hours</H3>  

<table border = 1>   

<tr>  

<th> Job Name </th> <th> Job Started </th> <th> Hours Run </th></tr>'  

SET @body = @body + @xml + '</table></body></html>'  

  

--check if the there is any data available before sending email.  

IF EXISTS (  

  SELECT 1  

  FROM @currently_running_jobs AS crj  

  INNER JOIN msdb..sysjobs AS jobs ON crj.job_id = jobs.job_id  

  INNER JOIN msdb..sysjobactivity AS ja ON ja.job_id = crj.job_id  

  WHERE crj.running = 1  

   AND ja.run_requested_date = (  

    SELECT max(ja1.run_requested_date)  

    FROM msdb..sysjobactivity AS ja1  

    WHERE ja1.job_id = crj.job_id  

    )  

   AND DATEDIFF(hour, ja.run_requested_date, getdate()) >= 5

    AND jobs.[name] NOT LIKE ('%Database Consistency%')  

  )  

BEGIN  

 EXEC msdb.dbo.sp_send_dbmail @recipients = 'ksubbareddy.sap@gmail.com'  

  ,@subject = @string  

  ,@body = @body  

  ,@body_format = 'HTML'  

  ,@importance = 'High'  

END  

ELSE  

 RETURN (0)  

  ---------------------------------------------------------------------------------------------------

USE [msdb]

GO


BEGIN TRANSACTION

DECLARE @ReturnCode INT

SELECT @ReturnCode = 0

IF NOT EXISTS (SELECT name FROM msdb.dbo.syscategories WHERE name=N'[On Demand]' AND category_class=1)

BEGIN

EXEC @ReturnCode = msdb.dbo.sp_add_category @class=N'JOB', @type=N'LOCAL', @name=N'[On Demand]'

IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback


END


DECLARE @jobId BINARY(16)

EXEC @ReturnCode =  msdb.dbo.sp_add_job @job_name=N'ADM - Long Running Jobs', 

@enabled=1, 

@notify_level_eventlog=0, 

@notify_level_email=2, 

@notify_level_netsend=0, 

@notify_level_page=0, 

@delete_level=0, 

@description=N'No description available.', 

@category_name=N'[On Demand]', 

@owner_login_name=N'sa', 

@job_id = @jobId OUTPUT

IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback

/****** Object:  Step [Long Running Jobs]    Script Date: 8/18/2025 6:54:54 AM ******/

EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'Long Running Jobs', 

@step_id=1, 

@cmdexec_success_code=0, 

@on_success_action=1, 

@on_success_step_id=0, 

@on_fail_action=2, 

@on_fail_step_id=0, 

@retry_attempts=0, 

@retry_interval=0, 

@os_run_priority=0, @subsystem=N'TSQL', 

@command=N'EXEC sp_longrunningjobs 8', 

@database_name=N'master', 

@flags=0

IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback

EXEC @ReturnCode = msdb.dbo.sp_update_job @job_id = @jobId, @start_step_id = 1

IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback

EXEC @ReturnCode = msdb.dbo.sp_add_jobschedule @job_id=@jobId, @name=N'Long Running Jobs', 

@enabled=1, 

@freq_type=4, 

@freq_interval=1, 

@freq_subday_type=4, 

@freq_subday_interval=30, 

@freq_relative_interval=0, 

@freq_recurrence_factor=0, 

@active_start_date=20160810, 

@active_end_date=99991231, 

@active_start_time=0, 

@active_end_time=235959, 

@schedule_uid=NULL;

IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback

EXEC @ReturnCode = msdb.dbo.sp_add_jobserver @job_id = @jobId, @server_name = N'(local)'

IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback

COMMIT TRANSACTION

GOTO EndSave

QuitWithRollback:

    IF (@@TRANCOUNT > 0) ROLLBACK TRANSACTION

EndSave:

GO



During SQL Server patching is when the SQL Server service fails to start after applying a patch

 One of the most frequent issues DBAs face during SQL Server patching is when the SQL Server service fails to start after applying a patch. 

This can be caused by various factors, such as corrupted system databases, incompatible configuration changes, or issues with disk space or permissions.


๐—ง๐—ต๐—ฒ ๐—œ๐˜€๐˜€๐˜‚๐—ฒ:

After applying Cumulative Updates or Service Packs, many DBAs experience failures where the SQL Server service doesn’t restart or the instance won’t come online. 

The root cause could range from corrupted system databases (like master, msdb, or model) to configuration conflicts or permission issues.

๐—–๐—ผ๐—บ๐—บ๐—ผ๐—ป ๐—–๐—ฎ๐˜‚๐˜€๐—ฒ๐˜€:

Corrupted system databases (master, msdb)

Incompatible configuration or parameter changes

Missing or incorrect permissions for SQL Server service account

Disk space issues or problems with SQL Server file access

Registry or dependency issues affecting the service

๐—ฅ๐—ฒ๐˜€๐—ผ๐—น๐˜‚๐˜๐—ถ๐—ผ๐—ป ๐—ฆ๐˜๐—ฒ๐—ฝ๐˜€:

๐—–๐—ต๐—ฒ๐—ฐ๐—ธ ๐—˜๐—ฟ๐—ฟ๐—ผ๐—ฟ ๐—Ÿ๐—ผ๐—ด๐˜€: Review SQL Server Error Logs and Windows Event Logs for specific errors.

๐—ฅ๐—ฒ๐˜€๐˜๐—ผ๐—ฟ๐—ฒ ๐—ฆ๐˜†๐˜€๐˜๐—ฒ๐—บ ๐——๐—ฎ๐˜๐—ฎ๐—ฏ๐—ฎ๐˜€๐—ฒ๐˜€: If corruption is detected, restore from a known good backup of system databases.

๐—–๐—ต๐—ฒ๐—ฐ๐—ธ ๐—–๐—ผ๐—ป๐—ณ๐—ถ๐—ด๐˜‚๐—ฟ๐—ฎ๐˜๐—ถ๐—ผ๐—ป: Ensure no conflicts with new settings introduced by the patch. Verify memory settings, tempdb, and other configurations.

๐—ฉ๐—ฒ๐—ฟ๐—ถ๐—ณ๐˜† ๐—ฃ๐—ฒ๐—ฟ๐—บ๐—ถ๐˜€๐˜€๐—ถ๐—ผ๐—ป๐˜€: Ensure the SQL Server service account has the necessary access to files and directories.

๐——๐—ถ๐˜€๐—ธ ๐—ฆ๐—ฝ๐—ฎ๐—ฐ๐—ฒ: Confirm sufficient disk space, especially for tempdb and transaction logs.

๐—ฅ๐—ฒ๐—ฎ๐—ฝ๐—ฝ๐—น๐˜† ๐—ฃ๐—ฎ๐˜๐—ฐ๐—ต ๐—ผ๐—ฟ ๐—ฅ๐—ฒ๐—ฝ๐—ฎ๐—ถ๐—ฟ ๐—œ๐—ป๐˜€๐˜๐—ฎ๐—น๐—น๐—ฎ๐˜๐—ถ๐—ผ๐—ป: If needed, reapply the patch or use SQL Server Setup to perform a repair.

๐—ฅ๐—ผ๐—น๐—น๐—ฏ๐—ฎ๐—ฐ๐—ธ ๐—ฃ๐—ฎ๐˜๐—ฐ๐—ต (๐—ถ๐—ณ ๐—ป๐—ฒ๐—ฒ๐—ฑ๐—ฒ๐—ฑ): If the issue persists, rollback the patch or restore from backup.

๐—ฃ๐—ฟ๐—ฒ๐˜ƒ๐—ฒ๐—ป๐˜๐—ถ๐—ผ๐—ป ๐—ง๐—ถ๐—ฝ๐˜€:

Always test patches in a non-prod environment first.

Backup critical system databases, especially master, before applying patches.

Document configurations before patching and monitor disk space and logs to detect issues early.

Patching is critical for SQL Server security and performance, but it’s vital to ensure a smooth patching process with proactive steps. Let’s keep SQL environments healthy and running!


Below query will get the table FK reference table list.

 Below query  will get the table FK reference table list. 

DECLARE @InputTableName NVARCHAR(128) = 'company_master';

 SELECT DISTINCT 

    OBJECT_NAME(fk.referenced_object_id) AS referenced_table
FROM sys.foreign_keys fk
WHERE OBJECT_NAME(fk.parent_object_id) = @InputTableName
  AND OBJECT_NAME(fk.referenced_object_id) IS NOT NULL
ORDER BY referenced_table;

 

 

Thursday, 14 August 2025

SQLDBA- verify the backup percentage on prem sql server

 SELECT

    db.name AS DatabaseName,

    r.command,

    r.status,

    r.percent_complete,

    r.start_time,

    r.estimated_completion_time / 1000 / 60 AS EstimatedCompletion_Minutes,

    r.total_elapsed_time / 1000 / 60 AS ElapsedTime_Minutes

FROM 

    sys.dm_exec_requests r

JOIN 

    sys.databases db ON r.database_id = db.database_id

WHERE 

    r.command IN ('BACKUP DATABASE', 'BACKUP LOG');


Monday, 11 August 2025

SQLDBA - SQL DBA Alert: Queries Suddenly Running Slow? Your Deep Dive Playbook

 As a SQL Server DBA, you’ll hear: “The app is slow!” or “Query took 2 seconds, now 2 minutes!” ๐Ÿ˜ฌ

Before diving in, follow this structured troubleshooting approach—to not just fix, but understand and prevent it.

๐Ÿ” Step 1: Immediate Triage: Global or Specific?

✅ Check if slowness is server wide or a few queries
Find top resource consumers:

SELECT TOP 10 total_elapsed_time/1000 AS ElapsedMS,
execution_count,
total_logical_reads,
(SELECT TEXT FROM sys.dm_exec_sql_text(sql_handle)) AS Query
FROM sys.dm_exec_query_stats
ORDER BY total_elapsed_time DESC;

๐Ÿ“ˆ Step 2: Live Monitoring: What’s Running Now?
Use Activity Monitor, sp_whoisactive, or:

SELECT * FROM sys.dm_exec_requests WHERE status = 'running';
Watch for:
Blocking
Wait types (sys.dm_os_waiting_tasks)
TempDB usage
CPU pressure

⏳ Step 3: Wait Stats: The Bottleneck Clues
Get current waits:

SELECT wait_type, wait_time_ms
FROM sys.dm_os_wait_stats
ORDER BY wait_time_ms DESC;
Patterns to note:
PAGEIOLATCH_* = Disk I/O
CXPACKET = Parallelism
LCK_* = Locking
SOS_SCHEDULER_YIELD = CPU

๐Ÿง  Step 4: Query Plans: Right Plan or Sniffed?
Use Query Store or:

SELECT qp.query_plan qt.text
FROM sys.dm_exec_query_stats qs
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) qp
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) qt
Look for:
Parameter sniffing
Stats issues
Index scans
Row estimation errors

๐Ÿ› ️ Step 5: Indexes & Stats: Healthy or Not?
Check index fragmentation:

SELECT * FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, 'SAMPLED');
Rebuild/reorganize as needed
Update stats:
EXEC sp_updatestats;

⚙️ Step 6: Blocking & Deadlocks
Run:
EXEC sp_who2;
SELECT * FROM sys.dm_tran_locks;
Capture deadlocks via Extended Events
Kill blockers carefully

๐Ÿงช Step 7: TempDB & I/O Checks
Monitor TempDB:
SELECT * FROM sys.dm_db_file_space_usage;
Check disk latency:
sys.dm_io_virtual_file_stats
Confirm enough TempDB files

๐Ÿ”„ Step 8: Recent Changes
Ask:
Any recent deployments?
Stats updated?
Indexes dropped?

๐Ÿ›ก️ Step 9: Quick Mitigations
Use RECOMPILE for sniffing
Add missing indexes (evaluate impact!)
Restart heavy agent jobs
Kill blockers (with caution)

๐Ÿงฐ Step 10: Prevent Future Issues
Enable Query Store
Use Extended Events
Set up alerts & monitoring
Automate index/stats jobs

SQLDBA- Deadlock graph query

  Dead lock graph query DECLARE @xelfilepath NVARCHAR(260) SELECT @xelfilepath = dosdlc.path FROM sys.dm_os_server_diagnostics_log_configura...