Friday, December 17, 2021

Get SQL statement using the sql_handle , start offset and end offset

We can use the below script to find the exact SQL statement using the sql_handle , start offset and end offset. 

 
DECLARE @sql_handle VARBINARY(64) = 0x0300050097E18713F1A9570113A8000001000000000000000000000000000000000000000000000000000000 --Pass sql handle here
DECLARE @offsetStart INT = 150 --Pass start offset here
DECLARE @offsetEnd INT = 326 --Pass End offset here

SELECT SUBSTRING(TEXT, (@offsetStart / 2) + 1, (
			(
				CASE @offsetEnd
					WHEN - 1
						THEN DATALENGTH(TEXT)
					ELSE @offsetEnd
					END - @offsetStart
				) / 2
			) + 1) AS statement_text
FROM sys.dm_exec_sql_text(@sql_handle)
/*
-- Get SQL TEXT and QUERY PLAN
select * from sys.[dm_exec_sql_text](0x02000000ACAC3005372F5458DAAFAAB4D6A72F99D43FBC080000000000000000000000000000000000000000) -- sql_handle
select * from sys.[dm_exec_query_plan](0x06000700ACAC3005C0DDD2E50100000001000000000000000000000000000000000000000000000000000000) -- plan_handle
go

*/


Done!! I hope this helps 😊

No comments:

Post a Comment

Extract DB Permission

Script to extract DB permissions   SET NOCOUNT ON GO SELECT 'Use ' + db_name ( ) PRINT 'go' GO SELECT 'EX...