1,使用SQL Server job
创建一个job用于执行package,可以制定一个schedule来定时执行job,也可以使用TSql 代码来执行job
EXEC msdb.dbo.sp_start_job N‘JOBNAME‘
msdb.dbo.sp_start_job 启动job,但是不等job运行完成,该stored procedure就立即返回,返回的结果标记job是否启动成功,可以通过msdb.dbo.sp_help_job 查看job的运行情况,示例代码如下
exec msdb.dbo.sp_help_job @job_name =N‘jobname‘,@job_aspect = ‘JOB‘
2,C#调用package
添加引用 Microsoft.SqlServer.DTSRuntimeWrap.dll
引入命名空间:using DtsRun = Microsoft.SqlServer.Dts.Runtime.Wrapper;
示例代码如下:
string strDtsxPath = @"D:\test.dtsx"; DtsRun.Application dtsApp = new DtsRun.Application(); DtsRun.IDTSPackage100 package = dtsApp.LoadPackage(strDtsxPath, true, null); DtsRun.DTSExecResult result = package.Execute(); //获取包的错误信息 //string message = string.Empty; //if (result.Equals(DtsRun.DTSExecResult.DTSER_FAILURE)) //{ // for (int i = 0; i < package.Errors.Count; i++) // { // message += package.Errors[i].Description; // } //}
如果报错,message 变量的信息是:“The Execute method on the task returned error code 0x80131621 (Mixed mode assembly is built against version ‘v2.0.50727‘ of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information.). The Execute method must succeed, and indicate the result using an "out" parameter.”
解决方案是配置App.config的节点: <startup useLegacyV2RuntimeActivationPolicy="true">
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>