How can I create a stored procedure to start a SQL Server job?
-- Create SQL Server Agent job start stored procedure with input parameter
CREATE PROC uspStartMyJob #MyJobName sysname
AS
DECLARE #ReturnCode tinyint -- 0 (success) or 1 (failure)
EXEC #ReturnCode=msdb.dbo.sp_start_job #job_name=#MyJobName;
RETURN (#ReturnCode)
GO
OR with no parameter:
-- Create stored procedure to start SQL Server Agent job
CREATE PROC StartMyMonthlyInventoryJob
AS
EXEC msdb.dbo.sp_start_job N'Monthly Inventory Processing';
GO
-- Execute t-sql stored procedure
EXEC StartMyMonthlyInventoryJob
EDIT FYI: You can use this PRIOR to starting IF you don't want to start the job IF it is running currently, work this in your stored proc:
-- Get run status of a job
-- version for SQL Server 2008 T-SQL - Running = 1 = currently executing
-- use YOUR guid here
DECLARE #job_id uniqueidentifier = '5d00732-69E0-2937-8238-40F54CF36BB1'
EXEC master.dbo.xp_sqlagent_enum_jobs 1, sa, #job_id
You can execute the stored procedure sp_start_job in your stored procedure.
See here: http://msdn.microsoft.com/en-us/library/ms186757.aspx
Create your store procedure and run the job inside your proc as follows:
DECLARE #JobId binary(16)
SELECT #JobId = job_id FROM msdb.dbo.sysjobs WHERE (name = 'JobName')
IF (#JobId IS NOT NULL)
BEGIN
EXEC msdb.dbo.sp_start_job #job_id = #JobId;
END
Related
I have an agent job that executes a .dtsx package. It needs to be called from a stored procedure owned by a database user, and used by the app and executes as owner.
Granted
Code:
DECLARE #return_value INT
EXEC #return_value = [dbo].[rscc_drop_off_caller]
SELECT 'Return Value' = #return_value
I gave the user SQLAgentUserRole and confirmed it has execute on sp_start_job.
If I run:
DECLARE #ReturnCode INT;
EXEC #ReturnCode = msdb.dbo.sp_start_job N'RSCC Push CCD To AIM';
PRINT #ReturnCode;
from a window in SSMS, it runs fine.
But if I run:
exec csisql.rscc_drop_off_caller;
it fails with an error:
Msg 229, Level 14, State 5, Procedure sp_start_job, Line 1
The EXECUTE permission was denied on the object 'sp_start_job', database 'msdb', schema 'dbo'.
The 'rscc_drop_off_caller' procedure attempted to return a status of NULL, which is not allowed. A status of 0 will be returned instead.
I even tried to drop and recreate the stored procedure after granting the permission but I get the same error. The stored procedure is pretty simple:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[rscc_drop_off_caller]
WITH EXECUTE AS OWNER
AS
DECLARE #ReturnCode int;
BEGIN
EXEC #ReturnCode = msdb.dbo.sp_start_job N'RSCC Push CCD To AIM';
RETURN (#ReturnCode);
END
Sorry if I provided too much information. I really need to get this working but I'm stumped. Any help would be REALLY appreciated. Thanks in advance.
KT
To summarize: I need to be able to call the agent job from within the stored procedure. That currently fails although calling the job directly (exec...) as the owning user works fine.
Thanks for the help. I resolved the issue. I modified the SP to execute as caller and granted specific permission to that DAimConnUser to execute the stored procedure.
I want to do something like this:
CREATE OR ALTER PROC myPROC
#myInput NVARCHAR(MAX)
AS
BEGIN
SELECT *
FROM myTABLE
-- I want this next command to run not to be stored for later execution.
EXEC RegisterProcSomewhere
END
GO
Is there a preferred way to do this? Essentially I want to collect metadata on my procedure when I CREATE/ALTER them.
Call it outside the proc to execute it immediately.
CREATE OR ALTER PROC myPROC
#myInput NVARCHAR(MAX)
AS
BEGIN
SELECT * FROM myTABLE
-------------------------------
END
GO
--I want this next command to run not to be stored for later execution.
EXEC RegisterProcSomewhere
From a TSQL Stored Procedure, I want to use the sp_add_jobstep stored procedure in the msdb database to create an SQL Agent job, which calls an SSIS package. I need to do this programmatically to dynamically set one of the parameters in the SSIS package at time of Job creation. In the "SQL Server Agent>Jobs>New Job" GUI, this is done under the "Steps>Edit>Configuration>Parameters" screen. How does one assign parameters with the sp_add_jobstep Stored Procedure?
The Microsoft documentation: https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-add-jobstep-transact-sql
does not explain this.
Related posts:
This post shows how to create an Agent job in T-SQL or C#: Create SQL Server Agent jobs programatically
And this post shows the SSIS syntax but does not discuss parameters: How do I create a step in my SQL Server Agent Job which will run my SSIS package?
As noted in the response by SAS, the params have to be passed as part of the command. The documentation for sp_add_jobstep shows a parameter called #additional_parameters, but notes this is not supported. So, while I didn't script it out (which would have been quicker), I did make an example job & then query the msdb.dbo.sysjobsteps table to see the format of the command. Based on that, and the earlier post by CSharper, I wrote the following stored procedure:
CREATE PROCEDURE [dbo].[CreateAgentjobHourlySSIS]
#job NVARCHAR(128),
#package NVARCHAR(max), -- \SSISDB\MyCatalog\MyProject\MyPackage.dtsx
#params NVARCHAR(max), -- /Par "\"$Project::MyParameter\"";ParameterValue /Par "\"$ServerOption::LOGGING_LEVEL(Int16)\"";1 /Par "\"$ServerOption::SYNCHRONIZED(Boolean)\"";True
#servername NVARCHAR(28),
#startdate DATE,
#starttime TIME,
#frequencyhours INT
AS
BEGIN TRY
BEGIN TRAN
--GRANT EXEC on CreateAgentjobHourlySSIS to PUBLIC
--1. Add a job
EXEC msdb.dbo.sp_add_job
#job_name = #job
--2. Add a job step named process step. This step runs the stored procedure
DECLARE #SSIScommand as NVARCHAR(max)
SET #SSIScommand = '/ISSERVER "\"'+#package+'\"" /SERVER "\"'+#servername+'\"" '+#params+' /CALLERINFO SQLAGENT /REPORTING E'
EXEC msdb.dbo.sp_add_jobstep
#job_name = #job,
#step_name = N'process step',
#subsystem = N'Dts',
#command = #SSIScommand
--3. Schedule the job starting at a specified date and time
DECLARE #startdateasint int = YEAR(#startDate)*10000+MONTH(#startdate)*100+DAY(#startdate)
DECLARE #starttimeasint int = DATEPART(HOUR,#starttime)*10000+DATEPART(MINUTE,#starttime)*100+DATEPART(SECOND,#starttime)
EXEC msdb.dbo.sp_add_jobschedule #job_name = #job,
#name = 'Hourly Schedule',
#freq_type = 4, --daily
#freq_interval = 1,
#freq_subday_type = 0x8, -- hourly
#freq_subday_interval = #frequencyhours,
#active_start_date = #startdateasint,
#active_start_time = #starttimeasint
--4. Add the job to the SQL Server
EXEC msdb.dbo.sp_add_jobserver
#job_name = #job,
#server_name = #servername
COMMIT TRAN
END TRY
BEGIN CATCH
SELECT ERROR_Message(), ERROR_Line();
ROLLBACK TRAN
END CATCH
You construct the call like this:
#command=N'/ISSERVER "
...
/Par "\"$Project::MyParam\"";ParamValue
...
If you already have a similar job you can right-click in SSMS and script it out.
That will show you the syntax.
I have created a stored procedure which calls other stored procedures but I don't want to execute them at the same time. Stored procedure #1 execution takes time so when it finishes stored procedure #2 will start to execute.
How can I do this?
EXEC SP1;
--wait for SP1 to finish its job
EXEC SP2;
Any suggestions?
It should be as simple as
EXEC SP1;
GO
EXEC SP2;
GO
Try using something like :
BEGIN TRY
BEGIN TRANSACTION
exec( #sp1)
exec(#sp2)
exec(#sp3)
COMMIT
END TRY
BEGIN CATCH
IF ##TRANCOUNT > 0 (Validate it )
ROLLBACK (rollback to sp where you want to )
END CATCH
How one can make an async call to a stored procedure from another one?
Assume I have two stored procedures, SP1 and SP2 (this is a long running stored procedure, takes much time to execute, and doesn't return any result).
The stored procedure SP1 is defined like this:
CREATE PROCEDURE SP1
AS
BEGIN
--custom business logic
--CALL to SP2, but async
EXEC SP2
END
How could you make a non-blocking/async call to SP like the above in SQL Server 2008/2012?
There was once I tried to achieve this by wrapping the stored procedure into Job, and then Calling the job in the procedure through sp_start_job system sp.
EXEC dbo.sp_start_job N'Job name' ;
Blockquote
Works as long as there are no arguments. – RoastBeast Dec 22 '15 at 17:30
Here's version with passing parameters
declare #variable -- job name
declare #command -- command
set #command = 'select * from table where data='+#variable
exec msdb..sp_add_job
#job_name =#variable,
#enabled=1,
#start_step_id=1,
#delete_level=1 --Job will delete itself after success
exec msdb..sp_add_jobstep
#job_name=#variable,
#step_id=1,
#step_name='step1',
#command=#command
exec msdb..sp_add_jobserver
#job_name = #variable,
#server_name = 'yourserver'
exec msdb..sp_start_job
#job_name=#variable