Run C# code inside a SQL Agent Job
I have a piece of code that needs to run every day at a开发者_如何学C 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.
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.
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.
You should read up on Sql Server Integration Services (SSIS). You can then schedule SSIS packages which are units of sql functionality. Within an SSIS package you can run script jobs and call CLR (Common Language Runtime - i.e. .Net jobs) functions to execute your .net code.
One thing though, you may be thinking about this in a slightly backwards fashion. Is the primary reason for using SSIS to schedule code executions which call some sql? If so, I'd recommend you research / use Windows Workflow Foundation (WWF). This is a .net framework for developing and running "long term" .net activities. On a simple level, you can think of it as the equivalent of SSIS for .Net programs. It can be built directly into your .Net applications without any sql server SSIS knowledge.
Finally, if your application is "very" simple you may wish to consider just wrapping up the database update calls in a simple Console Application. That way you could simply call the application via the Task Scheduler built into Windows to run at certain days / times etc.
You can create a .NET stored procedure, and add that to SQL Server. Then create a SQL Agent job that would call that new stored procedure.
The .Net stored procedure would essentially have to be limited to a small set of .NET libraries that are already embedded within SQL Server. You can add your own custom dlls to ensure that all required functionality will be available. However, given that there is a warning from MS that there is no guarantee that all custom dll's will work, it would simply require rigorous testing, to ensure that.
精彩评论