Run C# code inside a SQL Agent Job

Spread the love

Question Description

I have a piece of code that needs to run every day at a specified time. The code right now is sitting as a part of my web application. There are 2 stored procedures to get/save data that the code uses.

How can I setup Microsoft SQL Server Management Studio 2008 R2 to execute my code as well as the stored procs in a SQL Agent Job. I have never done this before and cannot seem to find the documentation.

Practice As Follows

The simplest method is to make a .NET console application that is just a shell for your real code sitting in a DLL or webservice or wherever. Then, in your SQL Agent job, create a step that is of type “Operating system (CmdExec)” that calls your console app. Saves you the hassle of SSIS (and that is one major hassle to avoid). I also agree with @Hasanain that a .NET proc might be another reasonable alternative.

enter image description here

One other thing to note. The SQL Agent CmdExec will look for an integer return code, so have your public static int Main(string args[]) {} method return 0 for success and some negative number for failure. Or, if you throw an exception, that’ll work just fine too. And the SQL Agent will log the text from whatever you threw since the console app will have written it to stdout/stderr.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.