Get duration of executing script in SQl Server 2008 R2 - sql

I have an script to execute and need executing time duration, how can I calculate it?
I think to use this way:
DECLARE #startTime DATETIME
SET #startTime = GETDATE();
--Script
DECLARE #endTime DATETIME
SET #endTime = GETDATE();
PRINT 'Transfer Duration:';
GO
PRINT CONVERT(varchar,#endTime-#startTime,14);
GO
But because I use GO (and I have to) so there is an error, So what is your suggestion to calculate and print duration of executing script (with Go) ?

Use a table to store the start and the end times, throw in your process ID also. Then use DATEDIFF() to calculate the time elapsed.
CREATE TABLE Profiling(
spid smallint NOT NULL,
StartTime DATETIME2 NOT NULL,
EndTime DATETIME2
)
INSERT INTO Profiling(spid, StartTime)
SELECT ##SPID, CURRENT_TIMESTAMP
GO
-- your queries come here
-- .....
UPDATE Profiling
SET EndTime = CURRENT_TIMESTAMP
WHERE spid = ##SPID
GO
SELECT DATEDIFF(MS, startTime, EndTime) as MilliSeconds
FROM Profiling
WHERE spid = ##SPID
Truncate the table from time to time, to avoid collisions of the spid's.

Look at SET STATISTICS TIME statement.

Go
DECLARE #startTime DATETIME
SET #startTime = GETDATE();
-- your sql statement
DECLARE #endTime DATETIME
SET #endTime = GETDATE();
PRINT 'Transfer Duration:';
PRINT cast((#endTime-#startTime) AS TIME);
Go
or to be more accurate you can use SET STATISTICS TIME which Displays the number of milliseconds required to parse, compile, and execute each statement.

Related

How to pass GETDATE (Only date) as a parameter in sql server?

I want to pass the system date (GETDATE) only as a parameter in my SQL stored procedure. But I am getting an error while executing the procedure.
SQL query:
ALTER PROCEDURE ST_PRO_GETUSER
#D DATETIME = GETDATE --// passing GETDATE as a parameter.
AS BEGIN
select case when branch in ('A25','B10','C10')
then 'BR B1' Else 'BR B2'
end As [COLLECTION],FIXDATE
from MAIN_COUNTER where TDATE=#D --//Just want to pass date only
group by COLLECTION,FIXDATE
END
EXEC KK_SP_GETUSER_DIV
Error:
Conversion failed when converting date and/or time from character string.
What I have to do for it?
To pass as a parameter you just declare a variable and pass it in:
DECLARE #DATE DATETIME = GETDATE();
EXEC ST_PRO_GETUSER #DATE;
And if you want the date only, change the datatype of your parameter to a date and then do:
DECLARE #DATE DATE = GETDATE();
EXEC ST_PRO_GETUSER #DATE;
But part of your question seems to actually be asking how to specify a default parameter value. You can't use a function for the default value, so instead do:
CREATE PROCEDURE ST_PRO_GETUSER
(
#Date DATETIME = null
-- Change to DATE datatype if you don't want a time component.
-- #Date DATE = null
)
AS
BEGIN
SET NOCOUNT ON;
-- Default the #Date here is its null.
-- Note this doesn't handle the case when the caller wants to pass in null.
SET #Date = COALESCE(#Date,GETDATE());
-- SP Body
RETURN 0;
END
Solved My Self
ALTER PROCEDURE ST_PRO_GETUSER
#Date datetime = null
as
IF #Date is null
SET #Date = getdate() --// passing GETDATE as a parameter.
BEGIN
select case when branch in ('A25','B10','C10')
then 'BR B1' Else 'BR B2'
end As [COLLECTION],FIXDATE
from MAIN_COUNTER where TDATE=#D --//Just want to pass date only
group by COLLECTION,FIXDATE
END
EXEC ST_PRO_GETUSER
GETDATE() is the correct syntax, not GETDATE.

Procedure time executing counter

I have got a procedure which inserts data from one table to other and one time it takes from example 5 minutes and next time for example 15 minutes.
I want to write code that create a log in my log table when procedure will take more then 10 minutes. Is exists any function or time counter in ms sql that I can use?
Add the following lines into your SP and it should work:
ALTER PROCEDURE YourSP
AS
BEGIN
DECLARE #StartTime AS DATETIME = GETDATE();
... <Your current lines>
IF DATEDIFF(mi, #StartTime, GETDATE()) > 10
INSERT INTO LogTable <YourFields>, MinutesSpent
VALUES <YourValues>, DATEDIFF(mi, #StartTime, GETDATE())
END
Why would you only log particular calls to the stored procedure? You should log all calls and filter out the ones that you want. This week you might be interesting in timings longer than 10 minutes. Next week, the data might grow and it might be 12 minutes.
Or you might change the code to make it more efficient, and it should finish in 2 minutes.
If you are only interested in timing, I would write a rather generic log table, something like this:
create table spTimeLog (
procedureName varchar(255),
startDateTime datetime
endDateTime datetime,
createdAt datetime default getdate()
);
create procedure usp_proc . . .
begin
declare #StartTime datetime = getdate();
. . .
insert into spTimeLog (procedureName, startDateTime, endDateTime)
values ('usp_proc', StartTime, getdate());
end;
Then you can get the information you want when you query the table:
select count(*)
from spTimeLog tl
where tl.procedureName = 'usp_proc' and
endDateTime > dateadd(minute, 10, startDateTime);
In general, when I write stored procedures for a real application, the stored procedures generate audit logs when they enter and exit -- both successfully and when they fail.
You can try this way
declare #start datetime = getdate()
-- your SQL statements
exec dbo.MyStoredProcedure
declare #executionTimeInMilliseconds int = datediff(ms, #start, getdate())

How to compare both date and time in T-SQL

I have an sql query where I want to compare BOTH the date and time because I am simulating both date and time. But it seems to be comparing the date part only. Here's the stored procedure:
Create PROCEDURE GPSTest_GPSEvent_DeleteOneUnit (#dateFrom DateTime, #dateTo DateTime, #gpsunit int)
AS
BEGIN
Delete from GPSEvent where GPSUnitID = #gpsunit and GPSEventDateTime between #dateFrom and #dateTo
return ##ROWCOUNT;
END
GO
I don't know if anyone has any idea why it's comparing the date part only?

Sql Server 2008 Clear Select statement cache?

Is there any possible that having a cache clear after performed a select statement?
I tried with one of my sql that at first time i execute it, its return me 3.15 minutes and second time(dint change any stuff) its return me 2.55 minutes.
Its is kind of tedious for me to test out the actual performance on the sql.
I found there is having cache on Sql Server 2005 on this post.
Am i correct about the cache having on sql server 2008?
This is what I do for the same purpose:
DBCC FREEPROCCACHE
DBCC DROPCLEANBUFFERS
GO
DROP TABLE [WHATEVER I NEED TO DROP]
GO
TRUNCATE TABLE [WHATEVER I NEED TO EMPTY]
GO
UPDATE [WHATEVER HAS TO BE "RESET"]
GO
[DO REST OF "RESET ACTIONS" HERE]
USE [YOUR DATABASE NAME]
GO
DECLARE #start_time datetime, #end_time datetime, #miliseconds int
DECLARE #ALL_YOUR_VARS -- _YOU'LL_USE_WHILE_YOU_MEASURE
/* BECAUSE YOU DON'T WANT TO MEASURE THE TIME SPENT ON TEMP VARS YOU CREATE FOR MEASURING EXEC TIME ONLY */
-- TODO: SET VARS' VALUES HERE, SAME REASON AS ABOVE
SET #start_time = GETDATE()
-- [EXECUTE ALL YOUR STATEMENTS HERE]
-- [YOU WANT TO MEASURE]
SET #end_time = GETDATE()
SET #miliseconds = DATEDIFF(ms, #start_time, #end_time)
SELECT #start_time, #end_time, CAST(#miliseconds AS VARCHAR(max)) + ' ms'
GO
EDIT: Almost forgot! You can also drop all active connections to your DB before start measuring (don't forget to create a new connection after you execute the code below as actual immediate window, from which you run the query will get disconnected too!!!)USE master
GO
SET NOCOUNT ON
DECLARE #DBName varchar(50)
DECLARE #spidstr varchar(8000)
DECLARE #ConnKilled smallint
SET #ConnKilled=0
SET #spidstr = ''
Set #DBName = 'YOURDBNAMEHERE'
IF db_id(#DBName) < 4
BEGIN
PRINT 'Connections to system databases cannot be killed'
RETURN
END
SELECT #spidstr=coalesce(#spidstr,',' )+'kill '+convert(varchar, spid)+ '; '
FROM master..sysprocesses WHERE dbid=db_id(#DBName)
IF LEN(#spidstr) > 0
BEGIN
EXEC(#spidstr)
SELECT #ConnKilled = COUNT(1)
FROM master..sysprocesses WHERE dbid=db_id(#DBName)
END

HH:MM:SS:Msec to HH:MM:SS in stored procedure

I have a stored procedure which update a table based on such calculation and the calculation is done as column name (Calendatedate) - (Current System Date Time) and update this information to a column (TimeSpent) and display the value in Hh:Mm:SS:Msec format.
The query is working fine but I want to update it in such a way so that the time spent should be only HH:MM:SS format. Please help me that how I remove that Msec from the time spent.
CREATE procedure St_Proc_UpdateTimeSpent
#timeEntryID int,
#status int output
as begin
set nocount on;
declare #Date dateTime;
set #Date=GETDATE();
update Production set TimeSpent=(SELECT CONVERT(VARCHAR(20),DateAdd(SS,Datediff(ss,CalendarDate, #Date)%(60*60*24),0),114)),
IsTaskCompleted=1
where productionTimeEntryID=#timeEntryID
set #status=1;
return #status;
end
You can just use style 108 instead of 114 in the CONVERT function to get only the hh:mm:ss:
CREATE PROCEDURE dbo.St_Proc_UpdateTimeSpent
#timeEntryID int,
#status int output
AS BEGIN
SET NOCOUNT ON;
DECLARE #Date DATETIME;
SET #Date = GETDATE();
UPDATE dbo.Production
SET TimeSpent = CONVERT(VARCHAR(20), DATEADD(SS, DATEDIFF(ss, CalendarDate, #Date)%(60*60*24),0), 108),
IsTaskCompleted = 1
WHERE
productionTimeEntryID = #timeEntryID
SET #status = 1;
RETURN #status;
END
See the excellent MSDN documentation on CAST and CONVERT for a comprehensive list of all supported styles when converting DATETIME to VARCHAR (and back)
BTW: SQL Server 2008 also introduced a TIME datatype which would probably be a better fit than a VARCHAR to store your TimeSpent values ... check it out!