Calculate execution time of a SQL query?

前端 未结 8 424
悲&欢浪女
悲&欢浪女 2020-12-04 14:17

I am providing search functionality in my website, when user searches a record then I want to display the time the query taken to get the results same as google does. When w

相关标签:
8条回答
  • 2020-12-04 14:44
    declare @sttime  datetime
    set @sttime=getdate()
    print @sttime
    Select * from ProductMaster   
    SELECT RTRIM(CAST(DATEDIFF(MS, @sttime, GETDATE()) AS CHAR(10))) AS 'TimeTaken'    
    
    0 讨论(0)
  • 2020-12-04 14:47

    try this

    DECLARE @StartTime DATETIME
    SET @StartTime = GETDATE()
    
      SET @EndTime = GETDATE()
      PRINT 'StartTime = ' + CONVERT(VARCHAR(30),@StartTime,121)
      PRINT '  EndTime = ' + CONVERT(VARCHAR(30),@EndTime,121)
      PRINT ' Duration = ' + CONVERT(VARCHAR(30),@EndTime -@starttime,114)
    

    If that doesn't do it, then try SET STATISTICS TIME ON

    0 讨论(0)
  • 2020-12-04 14:52

    I found this one more helpful and simple

    DECLARE @StartTime datetime,@EndTime datetime   
    SELECT @StartTime=GETDATE() 
    --Your Query to be run goes here--  
    SELECT @EndTime=GETDATE()   
    SELECT DATEDIFF(ms,@StartTime,@EndTime) AS [Duration in milliseconds]   
    
    0 讨论(0)
  • 2020-12-04 14:54

    Well, If you really want to do it in your DB there is a more accurate way as given in MSDN:

    SET STATISTICS TIME ON
    

    You can read this information from your application as well.

    0 讨论(0)
  • 2020-12-04 14:56

    We monitor this from the application code, just to include the time required to establish/close the connection and transmit data across the network. It's pretty straight-forward...

    Dim Duration as TimeSpan
    Dim StartTime as DateTime = DateTime.Now
    
    'Call the database here and execute your SQL statement
    
    Duration = DateTime.Now.Subtract(StartTime)
    Console.WriteLine(String.Format("Query took {0} seconds", Duration.TotalSeconds.ToString()))
    Console.ReadLine()
    0 讨论(0)
  • 2020-12-04 14:57

    Why are you doing it in SQL? Admittedly that does show a "true" query time as opposed to the query time + time taken to shuffle data each way across the network, but it's polluting your database code. I doubt that your users will care - in fact, they'd probably rather include the network time, as it all contributes to the time taken for them to see the page.

    Why not do the timing in your web application code? Aside from anything else, that means that for cases where you don't want to do any timing, but you want to execute the same proc, you don't need to mess around with something you don't need.

    0 讨论(0)
提交回复
热议问题