Monday, January 11, 2016

Tutorial - SQL Server 2014 Express - Job automation

Hi guys,

as you know, in Express Editions of Microsoft SQL Server the agent is not available. So it is difficult to create jobs, which run automated.
I've found a nice way via the command line to create automated SQL jobs without the SQL Server Agent.

First create your SQL statement and save it in an extra file. Name it i.e. "sqlCommand.sql".
Maybe you want to make a daily backup of your database, you create a statement like this, but it can be any valid SQL statement. This is just an example.

BACKUP DATABASE [db_myDatabase] TO  DISK = N'C:\Backup\SQL Server\db_myDatabase.bak' WITH NOFORMAT, INIT,  NAME = N'db_myDatabase-Full Database Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10, CHECKSUM
GO
declare @backupSetId as int
select @backupSetId = position from msdb..backupset where database_name=N'db_myDatabase' and backup_set_id=(select max(backup_set_id) from msdb..backupset where database_name=N'db_myDatabase' )
if @backupSetId is null begin raiserror(N'Verify failed. Backup information for database ''db_myDatabase'' not found.', 16, 1) end
RESTORE VERIFYONLY FROM  DISK = N'C:\Backup\SQL Server\db_myDatabase.bak' WITH  FILE = @backupSetId,  NOUNLOAD,  NOREWIND
GO


I you have Microsoft SQL Server 2014 Express installed, you can navigate via command line to the following directory:

"C:\Program Files\Microsoft SQL Server\110\Tools\Binn"

In this directory you find a executable named "sqlcmd.exe".


This executable you can use to execute your SQL Statement saved in your file "SqlCommand.sql".
Replace <server> with your server / machine name and <sqlInstance> with your instance of your SQL Server. The parameter -i tells the executable what SQL script should run. Replace it where your SQL script is saved.

sqlcmd -S <server>\<sqlInstance> -E -i "C:\Jobs\SQL Server\SqlCommand.sql"

When you press enter, the command(s) in your SQL script will be executed.
Now you just have  to create a simple command line script, which can be executed in a task scheduler job.

Command-line script:
c:
cd\
cd "C:\Program Files\Microsoft SQL Server\110\Tools\Binn"
sqlcmd -S <server>\<sqlInstance> -E -i "C:\Jobs\SQL Server\SqlCommand.sql"


That's it. :-)

No comments:

Post a Comment