job schedule to a SQL Job - sql-server

How do I schedule a job using sp_add_job to run every 5 minutes indefinitely?
What are the exact values of #freq_type=4,#freq_interval=64, freq_subday_type=0x4,#freq_subday_interval=10, #freq_relative_interval=0 that I should be using ?

Try this.... #user2748147
Declare #job nvarchar(128),
#mycommand nvarchar(max),
#servername nvarchar(28),
#databasename nvarchar(50),
#startdate nvarchar(8),
#starttime nvarchar(8)
SET #job = 'myJob'
SET #mycommand = 'Select * from myTable'
SET #startdate = '20151219' -- The date December 19, 2015
SET #starttime = '160000' -- The time, 16:00:00
SET #servername = 'myservername'
SET #databasename = 'yourdatabasename'
--Add a job
EXEC dbo.sp_add_job
#job_name = #job ;
--Add a job step named process step. This step runs the stored procedure
EXEC sp_add_jobstep
#job_name = #job,
#step_name = N'process step',
#subsystem = N'TSQL',
#database_name = #databasename,
#command = #mycommand
--Schedule the job at a specified date and time
exec sp_add_jobschedule #job_name = #job,
#name = 'MySchedule',
#freq_type=4,
#freq_interval=4,
#freq_subday_type=0x4,
#freq_subday_interval = 5,
#active_start_date = #startdate,
#active_start_time = #starttime
-- Add the job to the SQL Server Server
EXEC dbo.sp_add_jobserver
#job_name = #job,
#server_name = #servername

Related

Scheduling a SQL Job using sp_add_jobschedule

I was trying to add a job using sp_add_jobschedule. I was also given a very good link yesterday where I got some clues on how to create a job. While creating the stored procedure I am getting an error:
Msg 102, Level 15, State 1, Procedure Usp_Create_job, Line 19 [Batch Start Line 81]
Incorrect syntax near ';'.
Msg 2812, Level 16, State 62, Line 103
Could not find stored procedure 'sp_add_jobstep'.
Msg 2812, Level 16, State 62, Line 118
Could not find stored procedure 'dbo.sp_add_jobserver'.
Msg 137, Level 15, State 2, Line 127
Must declare the scalar variable "#Frequency".
I have used the following code to create the Stored Procedure.
create procedure Usp_Create_job
as
begin
declare #SP_Name varchar(max)
declare #JobName varchar(max)
declare #Step varchar(max)
declare #ScheduleName varchar(max)
declare #Frequency int
declare #Interval int
declare #Time int
declare #StartDate int
EXEC dbo.sp_add_job
#job_name = N'#JobName', -- passing job name through input parameter while executing SP Usp_Create_job
#category_name=N'[Uncategorized (Local)]',
#owner_login_name=N'sa',
#notify_level_eventlog=0 ;
GO
EXEC sp_add_jobstep
#job_name = N'#JobName', --passing job name through input parameter while executing SP Usp_Create_job
#step_id = 1,
#step_name = N'#Step', --passing step name through input parameter while executing SP Usp_Create_job
#subsystem = N'TSQL',
#command = N'
-- actual query
exec #SP_Name',
#retry_attempts = 0,
#retry_interval = 0,
#on_success_action = 1,
#database_name=N'Test' ;
GO
EXEC dbo.sp_add_jobserver
#job_name = N'#JobName', --passing job name through input parameter while executing SP Usp_Create_job
#server_name = N'(local)' ;
GO
EXEC sp_add_jobschedule
#job_name = N'#JobName',
#name = N'test job schedule',
#enabled = 1, --enabled
#freq_type = #Frequency, -- on daily basis input value 4
#freq_interval = #Interval,
#freq_subday_type = 1, -- units between each exec: seconds
#freq_subday_interval = 0, -- number of units between each exec
#active_start_date= #StartDate,
#active_end_date=99991231,
#schedule_uid=N'8912aa53-ffe9-4f31-b6cb-9a8e2f1ee6e3'
end
I have reviewed the code couple of times but was unable to find the exact issue. Any improvements will also be appreciated.
There are a number of issues with your code.
You can't have GO in the middle of a procedure, it signifies the end of a batch and a procedure must be a single batch.
The procedures are located in msdb, and it seems you want to create the procedure in that database. You need to switch to that database first.
You haven't defined parameters properly, you have just made local variables.
You cannot pass parameters contained in quotes, as that just means it will be looked at as a bare string such as '#SP_Name'
Some data types are wrong.
#schedule_uid is an output parameter, you do not need to pass it.
You are not passing in #ScheduleName.
The value for #active_end_date should be in quotes.
USE msdb;
GO
CREATE OR ALTER PROCEDURE Usp_Create_job
#SP_Name sysname
#JobName sysname,
#Step sysname,
#ScheduleName sysname,
#Frequency int,
#Interval int,
#Time int,
#StartDate int
AS
DECLARE #command nvarchar(max) = #command = N'
-- actual query
exec ' + QUOTENAME(#SP_Name) + '
-- more commands here
'
EXEC sp_add_job
#job_name = #JobName, -- passing job name through input parameter while executing SP Usp_Create_job
#category_name = N'[Uncategorized (Local)]',
#owner_login_name = N'sa',
#notify_level_eventlog = 0;
EXEC sp_add_jobstep
#job_name = #JobName, --passing job name through input parameter while executing SP Usp_Create_job
#step_id = 1,
#step_name = #Step, --passing step name through input parameter while executing SP Usp_Create_job
#subsystem = N'TSQL',
#command = #command,
#retry_attempts = 0,
#retry_interval = 0,
#on_success_action = 1,
#database_name = N'Test';
EXEC dbo.sp_add_jobserver
#job_name = #JobName, --passing job name through input parameter while executing SP Usp_Create_job
#server_name = N'(local)' ;
EXEC sp_add_jobschedule
#job_name = #JobName,
#name = #ScheduleName,
#enabled = 1, --enabled
#freq_type = #Frequency, -- on daily basis input value 4
#freq_interval = #Interval,
#freq_subday_type = 1, -- units between each exec: seconds
#freq_subday_interval = 0, -- number of units between each exec
#active_start_date = #StartDate,
#active_end_date = '99991231';
GO
Exactly why you would want this rather than just using SSMS's nice graphical interface is a different question...

Execute SSIS package and set package parameters in catalog

I have created a stored procedure to execute an ssis package in the catalog and set the package parameters dynamically at run time. I then create a job step to use the Operating system (CMDEXEC) Command to run the dtexec utility. The code is below:
ALTER PROCEDURE [Administration].[prc_Exec_LoadbenefitStatement_SSIS_TEST1]
#Destination varchar(250),
#FinancialFile varchar(250),
#StaticFile varchar(250),
#StatementType varchar(15),
#ExternalID varchar(20),
#SourceSystemID varchar(20)
AS
DECLARE #jid as uniqueidentifier
BEGIN TRANSACTION
SET NOCOUNT ON;
DECLARE #statement varchar(2000)
BEGIN
SET #statement = 'dtexec /ISServer "\SSISBD\AFFS\KhanyaStatements\Khanya_LoadBenefitStatement.dtsx" /SERVER "XXXXX\SQL01"'
SET #statement = #Statement + ' /Par "Destination";' + #Destination
SET #statement = #Statement + ' /Par "FinancialFile";' + #FinancialFile
SET #statement = #Statement + ' /Par "StaticFile";' + #StaticFile
SET #statement = #Statement + ' /Par "StatementType";' + #StatementType
SET #statement = #Statement + ' /Par "ExternalID";' + #ExternalID
SET #statement = #Statement + ' /Par "SourceSystemID";' + #SourceSystemID
END
DECLARE #jname varchar(128)
SET #jname = cast(newid() as char(36))
EXEC msdb.dbo.sp_add_job
#job_name = #jname,
#enabled = 1,
#category_name = 'KhanyaStatements_SSIS',
#delete_level = 3,
#job_id = #jid OUTPUT
EXEC msdb.dbo.sp_add_jobserver
#job_id = #jid,
#server_name = 'XXXXX\SQL01'
EXEC msdb.dbo.sp_add_jobstep
#job_id = #jid,
#step_name = 'Execute SSIS',
#subsystem = 'CMDEXEC',
#proxy_name = 'pr_KhanyaStatements',
#command = #statement
DECLARE #returncode tinyint
EXEC #returncode = msdb.dbo.sp_start_job
#job_id = #jid
SELECT #returncode
SET NOCOUNT OFF;
COMMIT TRANSACTION
I have created the Credential, Proxy and Job Category. When I execute the proc the return code is 0 for success but I can clearly see that the package did not execute. Please assist?

How to create the date wise backup file using T-SQL script

I wrote the following script but it shows an error due to the + sign in #command argument. Could anyone suggest how I can get rid of this error?
USE msdb;
GO
--add a job
EXEC dbo.sp_add_job
#job_name = N'FullBackup';
GO
USE msdb;
GO
--add jobsteps to jobsteps
DECLARE #fileName VARCHAR(90);
DECLARE #db_name VARCHAR(20);
DECLARE #fileDate VARCHAR(20);
DECLARE #commandtxt VARCHAR(100);
SET #fileName = 'D:\SQL server\BackUp\';
--SET #db_name = 'AdventureWorks_';
SET #fileDate = CONVERT(VARCHAR(8), GETDATE(),112);
SET #fileName = #fileName + #db_name + RTRIM(#fileDate) + '.bak';
SET #commandtxt = N'''BACKUP DATABASE [AdventureWorks2012] TO DISK =N''' + #fileName + ''' WITH INIT';
EXEC sp_add_jobstep
#job_name = N'FullBackup',
#step_name = N'Weekly Full Backup',
#subsystem = N'TSQL',
#command = 'BACKUP DATABASE [AdventureWorks2012] TO DISK =N''' + #fileName + ''' WITH INIT',
#retry_attempts = 5,
#retry_interval = 5;
GO
--Create a Schedule for this job, backup, occurs once a week each friday at 11:59
EXEC sp_add_schedule
#schedule_name = N'WeeklyBackup1',
#freq_type = 8,
#freq_interval = 32,
#freq_recurrence_factor = 1,
#active_start_time = 235900;
GO
--attach the schedule to the job
EXEC sp_attach_schedule
#job_name = N'FullBackup',
#schedule_name = N'WeeklyBackup1';
GO
EXEC dbo.sp_add_jobserver
#job_name = N'FullBackup';
GO
Try this
SET #commandtxt = N'BACKUP DATABASE [AdventureWorks2012] TO DISK =N''' + #fileName + ''' WITH INIT'
EXEC sp_add_jobstep
#job_name = N'FullBackup',
#step_name = N'Weekly Full Backup',
#subsystem = N'TSQL',
#command = #Commandtxt,
#retry_attempts = 5,
#retry_interval = 5;
GO
.
.
.

SQL Insert multiple records to Triggered table

On SQL Agent job I'm downloading data from main table (X). If the status equal 'WW' or 'WXY' I just want to all records insert into another table (Y) where I have created a trigger. Could you give me advise what should I change in my trigger definition? I receive error message when I try insert multiple records to DB2.Y table (agent job failed)
First code (downloading new data)
DECLARE #STARTTIME datetime
DECLARE #TIME datetime
DECLARE #ENDTIME datetime
SET #TIME=(SELECT MAX(Time) FROM DB2.Y)
SET #STARTTIME=(select dateadd(hour,1,getdate()))
SET #ENDTIME=(SELECT MAX(TIME) FROM DB1.X where TIME is not null)
IF #TIME = #ENDTIME
BEGIN
TRUNCATE TABLE DB2.Y;
INSERT INTO DB2.Y (Time) Values (#TIME)
END
ELSE
BEGIN
TRUNCATE TABLE DB2.Y
INSERT INTO DB2.Y ([Serv],[Status])
SELECT [SERV],[STATUS] FROM DB1.X WHERE TIME > #TIME and [SERV]='Description' and ([STATUS]='WW' or [STATUS]='WXY') ;
UPDATE DB2.Y
SET [Time]= #ENDTIME
END
The trigger code:
USE DB2
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[TriggerName] ON Y
AFTER INSERT AS
DECLARE #SERV varchar(40)
DECLARE #STATUS varchar(3)
SET #SERV=(SELECT [SERV] FROM inserted)
SET #STATUS=(SELECT [STATUS] FROM inserted)
IF #STATUS in ('WW', 'WXY')
BEGIN
DECLARE #MSG varchar(500)
SET #MSG = 'Job "' + #SERV + '" failed!!!'
EXEC msdb.dbo.sp_send_dbmail #recipients=N'myemail#domain.com', #body= #MSG, #subject = #MSG, #profile_name = 'profilename'
END
INSERTED can contain multiple rows for multi-row INSERTs - it runs once per operation, not once per row.
Try a trigger like this instead:
USE DB2
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[TriggerName] ON Y
AFTER INSERT AS
DECLARE #SERV varchar(40)
DECLARE #STATUS varchar(3)
IF EXISTS(SELECT [Status] FROM Inserted WHERE [STATUS] in ('WW', 'WXY'))
BEGIN
DECLARE #MSG varchar(8000)
INSERT INTO JobLog(Serv, Status)
SELECT Serv, Status FROM Inserted WHERE [STATUS] in ('WW', 'WXY')
SET #MSG = CAST(##ROWCOUNT as nvarchar) + 'Job(s) failed - see log for details'
EXEC msdb.dbo.sp_send_dbmail #recipients=N'myemail#domain.com', #body= #MSG, #subject = #MSG, #profile_name = 'profilename'
END
SELECT
Try something like this...
CREATE TRIGGER [dbo].[TriggerName] ON Y
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON;
DECLARE #SERV varchar(40),#STATUS varchar(3), #MSG varchar(500)
Select [SERV], [STATUS] INTO #Temp
FROM inserted
Where [STATUS] IN ('WW', 'WXY')
Declare Cur CURSOR FOR
SELECT [SERV], [STATUS] FROM #Temp
OPEN Cur
FETCH NEXT FROM Cur INTO #SERV, #STATUS
WHILE ##FETCH_STATUS = 0
BEGIN
SET #MSG = 'Job "' + #SERV + '" failed!!!'
EXEC msdb.dbo.sp_send_dbmail #recipients=N'myemail#domain.com'
, #body= #MSG
, #subject = #MSG
, #profile_name = 'profilename'
FETCH NEXT FROM Cur INTO #SERV, #STATUS
END
CLOSE Cur
DEALLOCATE Cur
END
You could use a cursor to resolve your error. The cursor below iterates over all inserted records with a STATUS of either WW or WXY and sends out an email for each of them.
DECLARE error_cursor CURSOR FOR
SELECT [SERV],[STATUS] FROM inserted
WHERE [STATUS] in ('WW', 'WXY')
OPEN error_cursor
FETCH NEXT FROM error_cursor
INTO #SERV, #STATUS
WHILE ##FETCH_STATUS = 0
BEGIN
DECLARE MSG varchar(500)
SET #MSG = 'Job "' + #SERV + '" failed!!!'
EXEC msdb.dbo.sp_send_dbmail #recipients=N'myemail#domain.com', #body= #MSG, #subject = #MSG, #profile_name = 'profilename'
FETCH NEXT FROM vendor_cursor
INTO #SERV, #STATUS
END
CLOSE error_cursor;
DEALLOCATE error_cursor;

MSSQL stored procedure call from ADO - not running properly

I have sp in MSSQL server - code below. When I run it from job, or SSMS it runs OK. But I need to run it from VB6 app with ADODB.
My VB6 code:
Dim cmd As New ADODB.Command
cmd.ActiveConnection = CNN
cmd.CommandTimeout = 180
cmd.CommandText = "dbbackup"
cmd.CommandType = ADODB.CommandTypeEnum.adCmdStoredProc
cmd.Execute(, , ADODB.ConnectOptionEnum.adAsyncConnect)
Problem is: When database backup is almost done - about 90+%, cmd.State changes from Executing to Closed and VB6 code continue in executing (to this moment it waits for sp to complete). But there is a lot of code after backup which never run this way(old backup delete,...). I realized that “Last database backup” property on MSSQL database was not set and in table msdb.dbo.backupset there are no rows for my backup. But there si good restorable backup on HDD.
When i stops program for 5 minutes in debug, sp runs properly to end and everything is OK. This backup code is last code in app run and after it ends program closes all connections and exits. I added wait to VB6 code and it helps on some servers, but many other servers still has same problem.
I think main question is why MSSQL server returns control flow to VB6 code and sp is not completed yet.
Thanks
sp code:
PROCEDURE [dbo].[dbBackup]
AS
BEGIN
SET NOCOUNT ON;
EXEC sp_configure 'show advanced options', 1
RECONFIGURE
EXEC sp_configure 'xp_cmdshell', 1
RECONFIGURE
If OBJECT_ID('tempdb..#DBName','u') IS NULL
Create Table #DBName
(
ID int identity (1,1) ,
Name varchar(128) not null ,
RetentionPeriod int null,
BackupPath varchar(255) default(''),
DBSize float default(0)
)
If OBJECT_ID('tempdb..#ExistingBackups', 'u') IS NULL
Create Table #ExistingBackups
(
Name varchar(128) ,
ID int identity (1,1)
)
Declare #Path varchar(255)
Declare #sql varchar(1000)
Declare #Name varchar(128)
Declare #RetentionPeriod int
Declare #LastBackupToKeep varchar(8)
Declare #ID int
Declare #MaxID int
Declare #eName varchar(255)
Declare #eMaxID int
Declare #eID int
Declare #eTimeStamp varchar(20)
Declare #errMsg nvarchar(2048)
Declare #errCount int; set #errCount = 0;
Declare #freeSpace bigint
Declare #pageSize float
Declare #dbSize bigint
Declare #procDate datetime
Declare #Sklad char(3)
Declare #backupName as varchar(255)
Select #pageSize = v.low / 1024 From master..spt_values v (noLock) Where v.number = 1 And v.[type] = 'E'
Select Top 1 #sklad = sklad_id From dbo.pohyb (noLock) Where Convert(int, sklad_id) > 500
Set #procDate = GETDATE()
Truncate Table #DBName
Insert Into #DBName (Name, RetentionPeriod, BackupPath)
Select DBName, BackupsToStore, BackupPath
From dbo.databaseBackup (noLock)
Where runBackup = 1
Select #MaxID = max(ID), #ID = 0 From #DBName
While #ID < #MaxID
Begin
Select #ID = min(ID) From #DBName Where ID > #ID
Select #Name = Name, #RetentionPeriod = RetentionPeriod, #Path = BackupPath
From #DBName
Where ID = #ID
If SUBSTRING(#Path, Len(#Path), 1) <> '\' Set #Path = #Path + '\'
Set #sql = 'Update #DBName Set DBSize= (Select Round(Sum(size) *' + CONVERT(varchar, #pageSize) + '/1024, 0) From ' + #Name + '.dbo.sysfiles (noLock)) Where Name = ''' + #Name + ''''
Exec (#sql)
Select #dbSize = DBSize From #DBName
--Exec #freeSpace = dbo.getDiskFreeSpace #drive = #Path
--If #freeSpace > #dbSize
--Begin
Set #eTimeStamp = REPLACE(REPLACE(CONVERT(varchar, #procDate, 113), ' ', '_'), ':', '-')
Set #sql = #Path + #Name + '_' + #eTimeStamp + '.bak'
Set #errMsg = 'OK'
Begin Try
SET #backupName = 'Objednavky backup by job ' + CONVERT(varchar, GETDATE(), 104) + ' ' + CONVERT(varchar, GETDATE(), 108);
Backup Database #Name To Disk = #sql
WITH NAME = #backupName;
-------mazanie backupu begin
Truncate Table #ExistingBackups
Set #sql = 'dir /B /OD ' + #Path + #Name + '_*.bak'
Insert #ExistingBackups Exec master..xp_cmdshell #sql
If Exists (Select 1 From #ExistingBackups Where PATINDEX('%File Not Found%', Name) > 0)
Truncate Table #ExistingBackups
Delete From #ExistingBackups Where Name IS NULL
Select #eID = 0
Select #eMaxID = Max(ID) - #RetentionPeriod From #ExistingBackups
While #eID < #eMaxID
Begin
Select #eID = Min(ID) From #ExistingBackups Where ID > #eID
Select #eName = Name From #ExistingBackups Where ID = #eID
Set #sql = 'del ' + #Path + #eName
Exec master..xp_cmdshell #sql
End
Truncate Table #ExistingBackups
-------mazanie backupu end
End Try
Begin Catch
Set #errMsg = #errMsg + '||' + CONVERT(varchar,ERROR_MESSAGE())
Set #errCount = #errCount + 1;
End Catch
--End
--Else
--Set #errMsg = 'Pln? disk (Vo?n? miesto: ' + CONVERT(varchar, #freeSpace) + ' MB, potrebn? aspo?: ' + CONVERT(varchar, #dbSize) + ' MB)'
Insert Into [dbo].[databaseBackup_log] ([Sklad_id], [DBName], [BackupDate], [Status]) Values (#Sklad, #Name, #procDate, Ltrim(Rtrim(CONVERT(varchar,#errMsg))))
End
Drop Table #DBName
Drop Table #ExistingBackups
IF #errCount > 0 BEGIN
RAISERROR (#errMsg, 16, 2) WITH SETERROR
END
RETURN 0;
END

Resources