May 04, 2012

SSIS Table To File Code

Sometimes I get request on how to do Table to Table ( Plenty of examples there),
Here is a Table to File.
Enjoy....
/*
   Microsoft SQL Server Integration Services Script Task
   Write scripts using Microsoft Visual C# 2008.
   The ScriptMain is the entry point class of the script.
*/

using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using Microsoft.SqlServer.Dts.Pipeline.Wrapper;
using Microsoft.SqlServer.Dts.Runtime.Wrapper ;
using Microsoft.SqlServer.Management.Sdk;


namespace ST_55a23d6382ef4a209443a3b35671622b.csproj
{
    [System.AddIn.AddIn("ScriptMain", Version = "1.0", Publisher = "", Description = "")]
    public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
    {

        #region VSTA generated code
        enum ScriptResults
        {
            Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
            Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
        };
        #endregion

        /*
        The execution engine calls this method when the task executes.
        To access the object model, use the Dts property. Connections, variables, events,
        and logging features are available as members of the Dts property as shown in the following examples.

        To reference a variable, call Dts.Variables["MyCaseSensitiveVariableName"].Value;
        To post a log entry, call Dts.Log("This is my log text", 999, null);
        To fire an event, call Dts.Events.FireInformation(99, "test", "hit the help message", "", 0, true);

        To use the connections collection use something like the following:
        ConnectionManager cm = Dts.Connections.Add("OLEDB");
        cm.ConnectionString = "Data Source=localhost;Initial Catalog=AdventureWorks;Provider=SQLNCLI10;Integrated Security=SSPI;Auto Translate=False;";

        Before returning from this method, set the value of Dts.TaskResult to indicate success or failure.
       
        To open Help, press F1.
    */

        public void Main()
        {
            // TODO: Add your code here
            Microsoft.SqlServer.Dts.Runtime.Package pgk = new Microsoft.SqlServer.Dts.Runtime.Package();
            pgk.Name = "ETL_ProcToFile";

            //Add SQL Source Component

            ConnectionManager SourceOLEDB = pgk.Connections.Add("OLEDB");
            SourceOLEDB.Name = "SOURCE";
            SourceOLEDB.ConnectionString = "ConnectionString Goes Here";


            //Add Flat File DB Connection info

            ConnectionManager FlatFileDestination = pgk.Connections.Add("FLATFILE");

            FlatFileDestination.ConnectionString = "Flat File full path goes here";
            FlatFileDestination.Name= "ReportDestination";

            FlatFileDestination.Properties["Format"].SetValue(FlatFileDestination, "Delimited");
            FlatFileDestination.Properties["ColumnNameInFirstDataRow"].SetValue(FlatFileDestination, true);

            //Add Data flow

            pgk.Executables.Add("STOCK:PipelineTask");

            Microsoft.SqlServer.Dts.Runtime.TaskHost taskHost = pgk.Executables[0] as Microsoft.SqlServer.Dts.Runtime.TaskHost;
            MainPipe dataFlowTask = (MainPipe)taskHost.InnerObject;

            // Add OLE-DB source component
            IDTSComponentMetaData100 componentSource = dataFlowTask.ComponentMetaDataCollection.New();
            componentSource.Name = "OLEDBSource";
            componentSource.ComponentClassID = "DTSAdapter.OleDbSource.2";

            // Get OLE-DB source design-time instance, and initialise component
            CManagedComponentWrapper instanceSource = componentSource.Instantiate();
            instanceSource.ProvideComponentProperties();

            // Set source connection
            componentSource.RuntimeConnectionCollection[0].ConnectionManagerID = SourceOLEDB.ID;
            componentSource.RuntimeConnectionCollection[0].ConnectionManager =
            DtsConvert.GetExtendedInterface (SourceOLEDB);

            // Set the source properties
            instanceSource.SetComponentProperty("AccessMode", 2);
            instanceSource.SetComponentProperty("SqlCommand", "SELECT * FROM sysobjects");

            // Reinitialize the metadata, refresh columns
            instanceSource.AcquireConnections(null);
            instanceSource.ReinitializeMetaData();
            instanceSource.ReleaseConnections();

            // Add Flat File destination
            IDTSComponentMetaData100 componentDestination = dataFlowTask.ComponentMetaDataCollection.New();
            componentDestination.Name = "FlatFileDestination";
            componentDestination.ComponentClassID = "DTSAdapter.FlatFileDestination.2";

            // Get Flat File destination design-time instance, and initialise component
            CManagedComponentWrapper instanceDestination = componentDestination.Instantiate();
            instanceDestination.ProvideComponentProperties();

            // Set destination connection
            componentDestination.RuntimeConnectionCollection[0].ConnectionManagerID = FlatFileDestination.ID;
            componentDestination.RuntimeConnectionCollection[0].ConnectionManager =
                DtsConvert.GetExtendedInterface(FlatFileDestination);

            // connecting
            IDTSPath100 path = dataFlowTask.PathCollection.New();
            path.AttachPathAndPropagateNotifications(componentSource.OutputCollection[0],
                componentDestination.InputCollection[0]);

            //  map columns
            IDTSInput100 destinationInput = componentDestination.InputCollection[0];
            IDTSVirtualInput100 destinationVirtualInput = destinationInput.GetVirtualInput();
            IDTSVirtualInputColumnCollection100 destinationVirtualInputColumns =
                destinationVirtualInput.VirtualInputColumnCollection;

            // Get native flat file connection
            Microsoft.SqlServer.Dts.Runtime.Wrapper.IDTSConnectionManagerFlatFile100 connectionFlatFile =
                FlatFileDestination.InnerObject as Microsoft.SqlServer.Dts.Runtime.Wrapper.IDTSConnectionManagerFlatFile100;

            // Create flat file connection columns to match pipeline
            int indexMax = destinationVirtualInputColumns.Count - 1;
            for (int index = 0; index <= indexMax; index++)
            {
                // Get input column to replicate in flat file
                IDTSVirtualInputColumn100 virtualInputColumn = destinationVirtualInputColumns[index];

                // Add column to Flat File connection manager
                Microsoft.SqlServer.Dts.Runtime.Wrapper.IDTSConnectionManagerFlatFileColumn100 flatFileColumn =
                    connectionFlatFile.Columns.Add() as Microsoft.SqlServer.Dts.Runtime.Wrapper.IDTSConnectionManagerFlatFileColumn100;
                flatFileColumn.ColumnType = "Delimited";
                flatFileColumn.ColumnWidth = virtualInputColumn.Length;
                flatFileColumn.DataPrecision = virtualInputColumn.Precision;
                flatFileColumn.DataScale = virtualInputColumn.Scale;
                flatFileColumn.DataType = virtualInputColumn.DataType;
                Microsoft.SqlServer.Dts.Runtime.Wrapper.IDTSName100 columnName = flatFileColumn as Microsoft.SqlServer.Dts.Runtime.Wrapper.IDTSName100;
                columnName.Name = virtualInputColumn.Name;

                if (index < indexMax)
                    flatFileColumn.ColumnDelimiter = ",";
                else
                    flatFileColumn.ColumnDelimiter = Environment.NewLine;
            }
            // Reinitialize the metadata, generating external columns from flat file columns
            instanceDestination.AcquireConnections(null);
            instanceDestination.ReinitializeMetaData();
            instanceDestination.ReleaseConnections();

            //  map destination columns
            foreach (IDTSVirtualInputColumn100 virtualInputColumn in destinationVirtualInputColumns)
            {
                // Select column, and retain new input column
                IDTSInputColumn100 inputColumn = instanceDestination.SetUsageType(destinationInput.ID, destinationVirtualInput, virtualInputColumn.LineageID, DTSUsageType.UT_READONLY);
                // Find external column by name
                IDTSExternalMetadataColumn100 externalColumn = destinationInput.ExternalMetadataColumnCollection[inputColumn.Name];
                // Map input column to external column
                instanceDestination.MapInputColumn(destinationInput.ID, inputColumn.ID, externalColumn.ID);
            }
                #if DEBUG
            // Save package to disk, DEBUG only
            Microsoft.SqlServer.Dts.Runtime.Application app = new Microsoft.SqlServer.Dts.Runtime.Application();
            app.SaveToXml(String.Format(@"C:\Temp\{0}.dtsx", pgk.Name), pgk, null);
            Console.WriteLine(@"C:\Temp\{0}.dtsx", pgk.Name);
                #endif

            pgk.Execute();

            foreach (DtsError error in pgk.Errors)
            {
                Console.WriteLine("ErrorCode       : {0}", error.ErrorCode);
                Console.WriteLine("  SubComponent  : {0}", error.SubComponent);
                Console.WriteLine("  Description   : {0}", error.Description);
            }

            pgk.Dispose();

            Dts.TaskResult = (int)ScriptResults.Success;
        }
    }
}

No comments:

Post a Comment

Contact Form

Name

Email *

Message *