Procedure time executing counter - sql

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

Related

Passing Date as a Parameter took more time to execute the procedure

I wrote a procedure to return a set of records for a report. If a date variable declared and assigned inside the procedure then it took 20 sec to execute and return the proper results. At the same time, date value passed as a parameter. It took more than 3 minutes (I have stopped the procedure execution).
1.Following procedure took only 20 sec to complete
CREATE PROCEDURE [dbo].[Month_OP_CL]
AS
BEGIN
DECLARE #RptDate DATE = CAST(DATEADD(DAY, -1, GETDATE()) AS DATE);
SELECT .....
END;
EXEC [dbo].[Month_OP_CL];
2.Following procedure took more than 3 minutes to complete
CREATE PROCEDURE [dbo].[Month_OP_CL]
(
#RptDate DATE
)
AS
BEGIN
SELECT .....
END;
DECLARE #RptDate DATE = CAST(DATEADD(DAY, -1, GETDATE()) AS DATE);
EXEC dbo.[Month_OP_CL] #RptDate.
Any mistakes?

Daylightsavings return 1 if select statment is empty, otherwise return 2

I am working on a daylight offset function and would like to hear your oppinion on how to solve this problem. Suppose I create a Stored Procedure which contains following code (input is the current time #time):
SELECT*
from
dbo.DaylightSavings
WHERE #time between Timestart AND Timeend
Now if the SELECT statement above returns a table view, then the dayligt savings should be ON and therefore the stored procedure should return an offset of +2. Otherwise, if the SELECT statement above does not return a table view then the daylightsavings should be OFF and the stored procedure would return +1 instead. How would I make a reasonable Stored Procedure which handles this logic?
thanks!
System:
MS SQL 2008R2
This should do what you want (assuming the 'offset' is hours):
DECLARE #Count INT
SET #Count = ( SELECT COUNT(*)
FROM
dbo.DaylightSavings
WHERE #time between Timestart AND Timeend)
IF #Count > 0
SELECT DATEADD(HH, 2, #time)
ELSE IF #Count = 0
SELECT DATEADD(HH, 1, #time)

Can you save and insert SQL Query Messages in a table?

I have a feeling this is an extremely newbie question, but it's hard to find the answer as anything to do with logging points me to SQL errors and issues. If not that, then the answer is querying the entire log to sift through.
When I insert data into an existing table via TSQL. How can I save or reference the Query Message for that specific statement? That way I can take the Query Message and insert the result into a log table that specifies how many records got inserted, maybe a duration of time it took and etc.
I'm using SQL Server 2008 R2 and these SQL statements are stored procedures inserting data and updating data. I want to ensure every step of the process is logged and inserted into a specific log table with details about that step of the process.
Thanks for your help on this (I'm assuming) newbie question. I'm still learning MSSQL.
DECLARE #dt DATETIME2(7), #duration INT, #rowcount INT;
SET #dt = SYSDATETIME();
INSERT dbo.foo(bar) VALUES('x');
SELECT #rowcount = ##ROWCOUNT, #duration = DATEDIFF(MICROSECOND, #dt, SYSDATETIME());
INSERT dbo.LoggingTable(duration,row_count) SELECT #duration, #rowcount;
In 2005 or lower, you can't get quite that precise, e.g.
DECLARE #dt DATETIME, ...
SET #dt = GETDATE();
...
... , #duration = DATEDIFF(MILLISECOND, #dt, GETDATE());

SQL stored procedure that needs to execute based on look up table value

I have a SQL stored procedure that needs to execute only if lookup table value has today's date.
If not then it should run again after 30 minutes with the same criteria.
How can I do that?
Look up table has just one date row value = '12-14-2012'. It will be change by another process.
Something like this can do it for you. Note this code will not execute, you will need to replace items with your values.
DECLARE #Today DATE
SET #Today = GETDATE()
IF EXISTS (SELECT 'x' FROM MyTable WHERE CAST(ColumnName as DATE) = #Today)
BEGIN
EXEC Sproc Here
END
At a high level, you can use SQL Server agent to schedule the proc. To decide whether or not to run you can put something like this in the proc
IF EXISTS(SELECT * FROM LOOKUP WHERE colname = convert(varchar, getdate(), 110))
BEGIN
--do stuff
END

Get duration of executing script in SQl Server 2008 R2

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.