问题
I want to create SQL Server Agent jobs programmatically. I am using the following code, while running it doesn't throw any error but when I check SQL Server Agent I don't see any jobs.
So question 1: is this the right way to create a job in msdb
from etgv125p (my database)
database?
When I use connectionString
with Initial Catalog=msdb
, I am getting an error
The EXECUTE permission was denied on the object 'CreateSQLAgentjobs', database 'msdb', schema 'dbo'
Question 2: what type of credentials do I need to have? I am already admin.
Code:
static void Main(string[] args)
{
string connetionString = "Data Source=SERVER;Initial Catalog=etgv125p;User ID=USER;Password=PASSWORD;Application Name=LOCAL";
//string connetionString = "Data Source=SERVER;Initial Catalog=msdb;User ID=USER;Password=PASSWORD;Application Name=LOCAL";
SqlConnection cnn = new SqlConnection(connetionString);
SqlCommand cmd = new SqlCommand();
string job = "Test_Job";
string command = "Test_StoredProc";
string serverName = "SERVERNAME";
string startDate = DateTime.Now.ToShortDateString();
string startTime = DateTime.Now.TimeOfDay.ToString();
try
{
cmd.CommandText = "CreateSQLAgentjobs";
cmd.Parameters.AddWithValue("@job", job);
cmd.Parameters.AddWithValue("@mycommand", command);
cmd.Parameters.AddWithValue("@servername", serverName);
cmd.Parameters.AddWithValue("@startdate", startDate);
cmd.Parameters.AddWithValue("@starttime", startTime);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = cnn;
cnn.Open();
cmd.ExecuteNonQuery(); // Error when using msdb connection string.
cnn.Close();
}
catch (Exception ex)
{
// ignored
}
}
Stored procedure:
ALTER PROCEDURE CreateSQLAgentjobs
@job NVARCHAR(128),
@mycommand NVARCHAR(max),
@servername NVARCHAR(28),
@startdate NVARCHAR(8),
@starttime NVARCHAR(8)
AS
BEGIN TRY
BEGIN TRAN
GRANT EXEC on CreateSQLAgentjobs 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
EXEC msdb.dbo.sp_add_jobstep
@job_name = @job,
@step_name = N'process step',
@subsystem = N'TSQL',
@command = @mycommand
--3. Schedule the job at a specified date and time
EXEC msdb.dbo.sp_add_jobschedule @job_name = @job,
@name = 'MySchedule',
@freq_type=1,
@active_start_date = @startdate,
@active_start_time = @starttime
--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
回答1:
for the error you are seeing for The EXECUTE permission was denied.... please open SSMS and execute the following code on a query tab:
GRANT EXEC on CreateSQLAgentjobs to PUBLIC
and remove it from the proc
来源:https://stackoverflow.com/questions/35135862/create-sql-server-agent-jobs-programatically