I was trying to write a powershell script to try find the top 2 running queries on a Azure SQL database and then capture the query plans of those 2 queries and then peform a DBCC cache free and capture those plans again after clearing the cache and send those plans to email using sendgird.
Issue1: plan handles stored in $delta2 are incorrect and doesn't work when used with sys.dm_exec_query_plan()
Issue 2: if i manage to get the correct handles from the sql studio and use them in $delta3 sys.dm_exec_query_plan() doesn't give any response in PowerShell
Issue 3: the Export-clixml corrpts the xml file and doesnt open in SQL studio.
Any help is much appreciated. Thanks in advance.
$params = @{
'Database' = 'xx'
'ServerInstance' = 'xx'
'Username' = 'xx'
'Password' = 'xxx'
'OutputSqlErrors' = $true
}
$sqlcmd= "
SELECT TOP 2
GETDATE() runtime, *
FROM (SELECT convert(VARCHAR(50), query_stats.query_hash, 1) as query_hash, SUM(query_stats.cpu_time) 'Total_Request_Cpu_Time_Ms', SUM(logical_reads) 'Total_Request_Logical_Reads', MIN(start_time) 'Earliest_Request_start_Time', COUNT(*) 'Number_Of_Requests', SUBSTRING(REPLACE(REPLACE(MIN(query_stats.statement_text), CHAR(10), ' '), CHAR(13), ' '), 1, 256) AS" + '"Statement_Text" '+"
FROM (SELECT req.*, SUBSTRING(ST.text, (req.statement_start_offset / 2)+1, ((CASE statement_end_offset WHEN -1 THEN DATALENGTH(ST.text)ELSE req.statement_end_offset END-req.statement_start_offset)/ 2)+1) AS statement_text
FROM sys.dm_exec_requests AS req
CROSS APPLY sys.dm_exec_sql_text(req.sql_handle) AS ST ) AS query_stats
GROUP BY query_hash) AS t
ORDER BY Total_Request_Cpu_Time_Ms DESC;"
$delta1 = Invoke-Sqlcmd -query $sqlcmd @params -MaxCharLength 999999
$qhash = $delta1.query_hash
$delta2 = "select convert(VARCHAR(100), plan_handle, 1) as plan_handle from sys.dm_exec_query_stats where query_hash = $qhash"
$getplanhandle = Invoke-Sqlcmd -query $delta2 @params -MaxCharLength 999999
$getplanhandle
foreach($plan in $getplanhandle)
{
$handle = $plan.plan_handle
$delta3 = "select * from sys.dm_exec_query_plan($plan.plan_handle)"
$saveplan = Invoke-Sqlcmd -query $delta3 @params -MaxCharLength 999999
$saveplan.query_plan | export-clixml -path ./query_plan.sqlplan
}
question from:
https://stackoverflow.com/questions/65854006/export-a-sql-plan-and-clear-the-plan-cache-of-azure-sql-database 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…