I want to execute a stored procedure automatically at every night. How can I do it. Please guide me with steps to achieve this target.
Thanks in advance.
Try this:
CREATE PROCEDURE MyTask
AS
BEGIN
SET NOCOUNT ON;
-- For executing the stored procedure at 11:00 P.M
declare @delayTime nvarchar(50)
set @delayTime = '23:00'
while 1 = 1
begin
waitfor time @delayTime
begin
--Name for the stored proceduce you want to call on regular bases
execute [DatabaseName].[dbo].[StoredProcedureName];
end
end
END
Then,
-- Sets stored procedure for automatic execution.
sp_procoption @ProcName = 'MyTask',
@OptionName = 'startup',
@OptionValue = 'on'
Reference:
sp_procoption (Transact-SQL)
Sets or clears a stored procedure for automatic execution. A stored procedure that is set to automatic execution runs every time an instance of SQL Server is started.
WaitFor
Blocks the execution of a batch, stored procedure, or transaction until a specified time or time interval is reached, or a specified statement modifies or returns at least one row.