programing

.NET에서 SSIS 패키지를 실행하는 방법은 무엇입니까?

iphone6s 2023. 6. 11. 10:25
반응형

.NET에서 SSIS 패키지를 실행하는 방법은 무엇입니까?

저는 SSIS 패키지를 가지고 있어서 결국 매개 변수를 전달하고 싶습니다. 이 매개 변수들은 .NET 응용 프로그램(VB 또는 C#)에서 올 것입니다. 그래서 저는 누가 이것을 하는 방법을 알고 있는지 궁금했습니다. 아니면 어떻게 하는지에 대한 유용한 힌트가 있는 웹 사이트입니다.

따라서 기본적으로 SSIS 패키지 매개 변수를 전달하는 .NET의 SSIS 패키지를 실행하여 SSIS 패키지 내에서 사용할 수 있습니다.

예를 들어 SSIS 패키지는 SQL db로 플랫 파일 가져오기를 사용하지만 파일의 경로 및 이름은 에서 전달되는 매개 변수일 수 있습니다.넷 애플리케이션.

코드에서 패키지의 변수를 설정하는 방법은 다음과 같습니다.

using Microsoft.SqlServer.Dts.Runtime;

private void Execute_Package()
    {           
        string pkgLocation = @"c:\test.dtsx";

        Package pkg;
        Application app;
        DTSExecResult pkgResults;
        Variables vars;

        app = new Application();
        pkg = app.LoadPackage(pkgLocation, null);

        vars = pkg.Variables;
        vars["A_Variable"].Value = "Some value";               

        pkgResults = pkg.Execute(null, vars, null, null, null);

        if (pkgResults == DTSExecResult.Success)
            Console.WriteLine("Package ran successfully");
        else
            Console.WriteLine("Package failed");
    }

SQL Server 2012와 함께 도입된 SSDB 카탈로그를 사용하는 방법은 다음과 같습니다.

using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.SqlClient;

using Microsoft.SqlServer.Management.IntegrationServices;

public List<string> ExecutePackage(string folder, string project, string package)
{
    // Connection to the database server where the packages are located
    SqlConnection ssisConnection = new SqlConnection(@"Data Source=.\SQL2012;Initial Catalog=master;Integrated Security=SSPI;");

    // SSIS server object with connection
    IntegrationServices ssisServer = new IntegrationServices(ssisConnection);

    // The reference to the package which you want to execute
    PackageInfo ssisPackage = ssisServer.Catalogs["SSISDB"].Folders[folder].Projects[project].Packages[package];

    // Add a parameter collection for 'system' parameters (ObjectType = 50), package parameters (ObjectType = 30) and project parameters (ObjectType = 20)
    Collection<PackageInfo.ExecutionValueParameterSet> executionParameter = new Collection<PackageInfo.ExecutionValueParameterSet>();

    // Add execution parameter (value) to override the default asynchronized execution. If you leave this out the package is executed asynchronized
    executionParameter.Add(new PackageInfo.ExecutionValueParameterSet { ObjectType = 50, ParameterName = "SYNCHRONIZED", ParameterValue = 1 });

    // Add execution parameter (value) to override the default logging level (0=None, 1=Basic, 2=Performance, 3=Verbose)
    executionParameter.Add(new PackageInfo.ExecutionValueParameterSet { ObjectType = 50, ParameterName = "LOGGING_LEVEL", ParameterValue = 3 });

    // Add a project parameter (value) to fill a project parameter
    executionParameter.Add(new PackageInfo.ExecutionValueParameterSet { ObjectType = 20, ParameterName = "MyProjectParameter", ParameterValue = "some value" });

    // Add a project package (value) to fill a package parameter
    executionParameter.Add(new PackageInfo.ExecutionValueParameterSet { ObjectType = 30, ParameterName = "MyPackageParameter", ParameterValue = "some value" });

    // Get the identifier of the execution to get the log
    long executionIdentifier = ssisPackage.Execute(false, null, executionParameter);

    // Loop through the log and do something with it like adding to a list
    var messages = new List<string>();
    foreach (OperationMessage message in ssisServer.Catalogs["SSISDB"].Executions[executionIdentifier].Messages)
    {
        messages.Add(message.MessageType + ": " + message.Message);
    }

    return messages;
}

코드는 http://social.technet.microsoft.com/wiki/contents/articles/21978.execute-ssis-2012-package-with-parameters-via-net.aspx?CommentPosted=true#commentmessage 을 약간 변형한 것입니다.

http://domwritescode.com/2014/05/15/project-deployment-model-changes/ 에도 비슷한 기사가 있습니다.

@Craig Schwarze 답변에 추가하자면,

다음은 몇 가지 관련 MSDN 링크입니다.

프로그래밍 방식으로 로컬 패키지 로드 및 실행:

프로그래밍 방식으로 원격 패키지 로드 및 실행

실행 중인 패키지에서 이벤트 캡처:

using System;
using Microsoft.SqlServer.Dts.Runtime;

namespace RunFromClientAppWithEventsCS
{
  class MyEventListener : DefaultEvents
  {
    public override bool OnError(DtsObject source, int errorCode, string subComponent, 
      string description, string helpFile, int helpContext, string idofInterfaceWithError)
    {
      // Add application-specific diagnostics here.
      Console.WriteLine("Error in {0}/{1} : {2}", source, subComponent, description);
      return false;
    }
  }
  class Program
  {
    static void Main(string[] args)
    {
      string pkgLocation;
      Package pkg;
      Application app;
      DTSExecResult pkgResults;

      MyEventListener eventListener = new MyEventListener();

      pkgLocation =
        @"C:\Program Files\Microsoft SQL Server\100\Samples\Integration Services" +
        @"\Package Samples\CalculatedColumns Sample\CalculatedColumns\CalculatedColumns.dtsx";
      app = new Application();
      pkg = app.LoadPackage(pkgLocation, eventListener);
      pkgResults = pkg.Execute(null, null, eventListener, null, null);

      Console.WriteLine(pkgResults.ToString());
      Console.ReadKey();
    }
  }
}

그래서 어떤 언어에서든 실제로 발사할 수 있는 또 다른 방법이 있습니다.제가 생각하는 가장 좋은 방법은 .dtsx 패키지를 호출하는 배치 파일을 만드는 것입니다.

그런 다음 모든 언어에서 배치 파일을 호출합니다.윈도우 플랫폼에서와 마찬가지로, 어디서든 배치 파일을 실행할 수 있으며, 이것이 당신의 목적에 가장 일반적인 접근 방식이 될 것이라고 생각합니다.코드 종속성이 없습니다.

자세한 내용은 아래 블로그에서 확인할 수 있습니다.

https://www.mssqltips.com/sqlservertutorial/218/command-line-tool-to-execute-ssis-packages/

해피 코딩..:)

고마워, Ayan

SSIS에 변수가 있는 경우 이 기능을 사용할 수 있습니다.

    Package pkg;

    Microsoft.SqlServer.Dts.Runtime.Application app;
    DTSExecResult pkgResults;
    Variables vars;

    app = new Microsoft.SqlServer.Dts.Runtime.Application();
    pkg = app.LoadPackage(" Location of your SSIS package", null);

    vars = pkg.Variables;

    // your variables
    vars["somevariable1"].Value = "yourvariable1";
    vars["somevariable2"].Value = "yourvariable2";

    pkgResults = pkg.Execute(null, vars, null, null, null);

    if (pkgResults == DTSExecResult.Success)
    {
        Console.WriteLine("Package ran successfully");
    }
    else
    {

        Console.WriteLine("Package failed");
    }

언급URL : https://stackoverflow.com/questions/273751/how-to-execute-an-ssis-package-from-net

반응형