SSMS Set Statistics Time On/Off prints multiple lines instead of just one

170 Views Asked by At

When I run my query, it prints multiple execution times instead of just one. I only want one so what do I need to do to get this to only print one time stamp?

SET STATISTICS TIME ON
DECLARE @firstNum INT, @secondNum INT, @thirdNum INT, @evenSum INT
SET @firstNum = 1
SET @secondNum = 2
set @thirdNum = 2
SET @evenSum = 2
WHILE (@thirdNum <= 4000000)
BEGIN
    SET @thirdNum = @firstNum + @secondNum
    SET @firstNum = @secondNum
    SET @secondNum = @thirdNum
    IF (@thirdNum % 2) = 0
    SET @evenSum += @thirdNum
END
PRINT 'Answer = ' + CONVERT(VARCHAR, @evenSum)
SET STATISTICS TIME OFF
2

There are 2 best solutions below

3
zealous On BEST ANSWER

If you remove PRINT 'Answer = ' + CONVERT(VARCHAR, @evenSum) from your code then it won't print multiple execution time.

Here is the example of it.

1
Nikki On

Statistic time will print for each execution. Since you are looping you are performing multiple query statements (I believe this also applies for sets -i could be wrong though), each will provide an execution time. There really is no way to modify statistic time for what I think you are looking for.

You could declare a datetime2 and store the start time in the beginning by using SysDateTime, and get the end time upon completion, thus printing the difference onto the screen using DateDiff. (This will achieve what you are asking for. )

You could also look into client statistic (but that might not be what you want).

Side note and irrelevant: you are looping queries. This is not profient and you may be doing this to learn. I would recommend looking into Tally tables for replacing loops. You can greatly improve performance if you design your query correctly.