Run C# code inside a SQL Agent Job

社会主义新天地 提交于 2019-11-30 08:37:24

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!