Export SQL Jobs from Command Prompt using OSQL

Posted on 2009-05-13
Last Modified: 2012-05-07
I found this posting, but I'm completely lost in how to do this.

My need is backup several databases and all the SQL Jobs (Stored Procedures?) from our servers. To make the task easier, I have written a .bat file that can be run on each of the servers to do this. So far, all the databases are being backed up good, I just can't seem to get the SQL Jobs. I know you can right-click on Jobs under SQL Server Agent in Enterprise Manager and generate the SQL script that I can save and use to restore the server. My problem is I can't figure out how they are doing it in the other post.

I know very little about databases, and queries. Can anyone shed some light for me?
Question by:ninebal
  • 5
  • 3
LVL 51

Accepted Solution

Mark Wills earned 500 total points
ID: 24382878
Well they are contained in the MSDB database, so you could include that in your backups...

Do you actually need to run scripts ?

You can do this by code :

or, using EM :
1) Open the SQL Server Enterprise Manager, and then expand the Management folder.
2) Expand SQL Server Agent, and then either right-click Alerts, Jobs, or Operators.
3) Click All Tasks, and then click Generate SQL Script.

Which should only be needed when there is a change...

If you are trying to export DTS jobs, then you can also use something like :


Author Comment

ID: 24385681
I tried to run that script from the link you specified and below is what I got. However it is only getting about 1/2 the SQL jobs. There is an error at line 46. I'm not familiar with SQL to figure out what it is.

***Note I edited the database and table names in this post.
Error MessageServer: Msg 14266, Level 16, State 1, Procedure sp_verify_jobstep, Line 46

The specified '@step_id' is invalid (valid values are: 1..1).

Server: Msg 14266, Level 16, State 1, Procedure sp_verify_jobstep, Line 46

The specified '@step_id' is invalid (valid values are: 1..1).

Code from the Script:

  execute @ReturnCode = msdb.dbo.sp_add_jobstep @job_id = @JobID , @step_id = 3, @cmdexec_success_code = 0, @on_success_action = 1, @on_success_step_id = 0, @on_fail_action = 2, @on_fail_step_id = 0, @retry_attempts = 4, @retry_interval = 1, @os_run_priority = 0, @flags = 0, @step_name = N'Update xxxxx_Cfg if success', @subsystem = N'TSQL', @command = N'UPDATE XXXXX_STATION_CFG

			SET Value = ''Maintenance Complete''

			WHERE Parameter = ''Central_DB_Status''

			AND Value = ''Database Maintenance''


			SET Value = '' ''

********Line 45********	WHERE Parameter = ''Maint_End_Datetime''

********Line 46********

********Line 47********	UPDATE xxxxx_STATION_CFG 

			SET value = ''NO''

			WHERE Parameter = ''MAINT_READY''

			AND Value = ''YES''', @database_name = N'xxxxx_DATA'

Code from Generate SQL:

  EXECUTE @ReturnCode = msdb.dbo.sp_add_jobstep @job_id = @JobID, @step_id = 3, @step_name = N'Update xxxxx_Cfg if success', @command = N'UPDATE xxxxx_STATION_CFG

			SET Value = ''Maintenance Complete''

			WHERE Parameter = ''Central_DB_Status''

			AND Value = ''Database Maintenance''


			SET Value = '' ''

			WHERE Parameter = ''Maint_End_Datetime''


			SET value = ''NO''

			WHERE Parameter = ''MAINT_READY''

Open in new window

LVL 51

Expert Comment

by:Mark Wills
ID: 24386960
It looks like the script is generating far too much information - if you were to comment out the success/fail steps and setting in the top line, I think it will work properly. It appears to be trying to accommodate error steps and they do not exist.

But I am a bit confused...

I thought you were wanting to create backups of those jobs, not to run them.

Are the other missing jobs DTS ?


Author Comment

ID: 24389568
Commenting out the success/fail steps will not work in my situation.

This script will be run remotely on each of the servers, and will be used to recover the server in the event of a failure. Having to "customize" the script for each server will not work in our situation. I was looking for a general script to backup the SQL jobs on any server.

Something like this I use on the databases:
osql -U <USERNAME> -P <PASSWORD> -Q "backup database <DATABASE> to disk = '<PATH>\<DATABASE>' with init"

That script will backup any database to any location. Maybe I'm not explaining my needs very good, and I apoloigize for that.
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

LVL 51

Expert Comment

by:Mark Wills
ID: 24390533
You are explaining well enough, but, there is always a possibility of a reader misunderstanding (ie me)....

For recovery purposes, all you have to do is to ensure Master, MSDB and maybe Model (though of lesser importance unless you are actively using it).

Have a look at :;EN-US;Q307775

There are external DTS packages that you would have to include in that strategy, but being external, they are probably already part of the physical backup strategy.
LVL 51

Expert Comment

by:Mark Wills
ID: 24390610
Sorry, that didn't make sense....

Backup Master (contains users, security etc) and MSDB (Jobs, Mail etc). You can restore them but the System Databases do require special attention.

For DR type processes with SQL 2000 have a look at  :;EN-US;Q307775


Author Closing Comment

ID: 31581897
The databases we use in our system are created during the software install process on the server, so there is no need to get the other databases but the 3 or 4 that our software uses. During out recovery process, we use a boot disk to grab files and folders and the MDF and LDF's. Then we reinstall the software and restore the data. If it's a hardware failure, we can just use the same drives, but when Windows crashes (rarely happens right?) then we need to go through this recovery\re-installation process. So those links do not apply. We have tried restoring the master DB and there are issues with SIDS and QUIDS.

I guess ultimatly, I was hoping to get a batch file that I can schedule to run that would automatically run. This is part of that and it's 95% of the way there. Getting the SQL jobs, and the Desktop are the only 2 things left I need to work out.

By the way, getting the desktop stuff is annoying me too! For some reason and I have no clue why, there are 2 or 3 folders they are stored in. AllUsers\desktop, administrator\desktop, and administrator.\desktop. The problem is getting the last folder as there is no way to be sure what it is unless you look at the folder. To be honest, I'm not too worried about that. In any case when recovering a server, you will have to be in the file system and to grab the desktop manually instead of the entire server is still a pretty big improvement over our old process.

Getting the SQL jobs is more iceing on the cake thing. It's something we never did before. We do not support the custom jobs the customer may create. I was just trying to get them.

With the info you have given me, I can now go to our DBA's and ask them for assistance. Great job and easy to follow instructions.

By the way, I was told by 1 DBA that he didn't think there was a way to get the jobs using QSQL.
LVL 51

Expert Comment

by:Mark Wills
ID: 24395971
Great reply, thanks so much for that...

Restoring Master does have more than a few challenges. It can be done, and depending on your site, needs to be done to restablish the users, logins and security.

The MSDB database is not quite as challenging, you can restore it, and arguably better by script so long as SQL Agent is not running :

As for files in folders, wouldn't they be part of the physical disk backup ? Do you really have to script everything ? Someone will have to interven to re-establish a few things, and whilst it would be ideal to automate the whole lot, sometimes a well written procedure is not such an overhead...

Love to see the look on your DBA's face when you show the script :)

If you are so inclined, stop by and let us know how you go...

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
sql query help 4 45
xpath sql query 2008 8 44
Make query more efficient 1 18
Extract string portion 2 16
Composite queries are used to retrieve the results from joining multiple queries after applying any filters. UNION, INTERSECT, MINUS, and UNION ALL are some of the operators used to get certain desired results.​
Read about achieving the basic levels of HRIS security in the workplace.
Video by: Steve
Using examples as well as descriptions, step through each of the common simple join types, explaining differences in syntax, differences in expected outputs and showing how the queries run along with the actual outputs based upon a simple set of dem…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

863 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

28 Experts available now in Live!

Get 1:1 Help Now