简体   繁体   中英

How can I display the Executing Query % which is enabled by Live Query Statistics in MSSQL in a windows form using C#?

In SSMS, when I enable the Live Query Statistics, I can see the execution percentage on the bottom left of the window.

在此输入图像描述

I want to display this incrementing percentage to the end user on a windows form. So far, I tried to implement this using progress bar on Visual Studio but turns out until I use a data table, it's not possible.

在此输入图像描述

Forget the progress bar, even if I could display the incremental percentage in a text format on a label - exactly like in SSMS it will do the job.

Any suggestions to implement the code in C# would be helpful.

On SQL Server 2016 SP1+ it can be done via dm_exec_query_profiles:

-- to enable LQS infrastructure, you have to do it once, also it can be set a startup trace:
DBCC TRACEON(7412, -1)

-- Session to track:
DECLARE @YourSessin INT = 760

-- Query that track a progress
SELECT  session_id ,
        node_id ,
        physical_operator_name ,
        SUM(row_count) row_count ,
        SUM(estimate_row_count) AS estimate_row_count ,
        IIF(COUNT(thread_id) = 0, 1, COUNT(thread_id)) [Threads] ,
        ISNULL(CAST(SUM(row_count) * 100. / NULLIF(SUM(estimate_row_count),0) AS DECIMAL(30, 2)),0) [PercentComplete] ,
        CONVERT(TIME, DATEADD(ms, MAX(elapsed_time_ms), 0)) [Operator time] ,
        DB_NAME(database_id) + '.' + OBJECT_SCHEMA_NAME(QP.object_id,
                                                        qp.database_id) + '.'
        + OBJECT_NAME(QP.object_id, qp.database_id) [Object Name]
FROM    sys.dm_exec_query_profiles QP
WHERE QP.session_id = @YourSessin
GROUP BY session_id ,
        node_id ,
        physical_operator_name ,
        qp.database_id ,
        QP.OBJECT_ID ,
        QP.index_id
ORDER BY session_id ,
        node_id

And more compact version:

DBCC TRACEON(7412, -1)

DECLARE @YourSessin INT = 760

SELECT MIN( CAST(row_count * 100. / NULLIF(estimate_row_count,0) AS DECIMAL(30, 2))) [PercentComplete]         
FROM    sys.dm_exec_query_profiles QP 
WHERE QP.session_id = @YourSessin

Please note, that enabling LQS infrastructure will add some overhead. According to MS, if SQL Server 2016 SP1+ it is 1-2%. In older versions it raise up to 75%

In SQL Server 2019 LQS is enabled by default, so no actions needed.

More information on topic in a recent thread: https://dba.stackexchange.com/questions/228957/sql-server-2014-view-any-live-execution-plan-in-activity-monitor/228958#228958

Another warning is about accuracy: calculations are based on estimate_row_count of the query plan, therefore estimations can be very rough, especially if statistics are not up to date

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM