Calculate execution time of a SQL query?

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 we search anything then google displays how much time it takes to get results?

For this I have declared a @start variable in my SP and finding the difference in the end, as below;

DECLARE @start_time DATETIME

SET @start_time = GETDATE()

-- my query
SELECT * FROM @search_temp_table

SELECT RTRIM(CAST(DATEDIFF(MS, @start_time, GETDATE()) AS CHAR(10))) AS 'TimeTaken'

Is there any other easy and fast way, or a single line of query with which we can find out the time a query taken to execute?

I'm using SQL Server 2005.


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.


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]   

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()