本文介绍了使用SSIS脚本任务将数据从多个SQL表导出到不同的平面文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个datagrid并使用VB.NET将内容导出到一个文本文件,我正在SSIS脚本任务中执行此操作,以便自动化将动态表导出到文本文件的过程。我没有得到任何错误,文件被创建,但文件是空的。



我在这段代码中错了什么?

 公开Sub Main()

Dim FName As String =D:\test.TXT

'''''''''''''''' '''''''''''''''''''$'$ b如果File.Exists(FName)然后
File.Delete(FName)
End If
''''''''''''''''''''''''''''''''''''

Dim myConnection As OleDbConnection = New OleDbConnection(Data Source = localhost; Provider = SQLNCLI10; Initial Catalog = AdventureWorksDW2008R2; Integrated Security = SSPI)
Dim da As OleDbDataAdapter = New OleDbDataAdapter select * from Table)
Dim ds As DataSet = New DataSet

da.Fill(ds,Test)

Dim DataGrid1 As New DataGrid
DataGrid1.DataSource = ds.DefaultViewManager
Dim DataGridView1作为新数据GridView

DataGridView1.DataSource = ds

Dim dgvc As DataGridViewCell
Dim sw As New System.IO.StreamWriter(FName)

对于每个dgvr作为DataGridViewRow在DataGridView1.Rows

Dim intCellCount As Integer = dgvr.Cells.Count
Dim intCounter As Integer = 1

对于每个dgvc在dgvr .Cells()
如果intCounter<> intCellCount然后
sw.Write(dgvc.Value.ToString&|​​)
Else
sw.WriteLine(dgvc.Value.ToString)
End If

intCounter + = 1
下一个
下一个

Dts.TaskResult = ScriptResults.Success

End Sub


解决方案

这是一种将不同结构的表导出到平面文件的可能方法,使用脚本任务。此示例将使用脚本任务将包含不同字段和数据的两个表导出到平面文件。为了导出数据,您可以使用 DataReader 而不是使用 DataGrid 。可能还有其他可能的方式来做到这一点。



分步过程


  1. 创建三个名为的表dbo.TablesList dbo.Source1 dbo.Source2 使用 SQL脚本部分下的脚本。

  2. 填充表 dbo.TablesList dbo.Source1 和dbo.Source2,数据显示在截图# 1

  3. 在SSIS包的连接管理器中,创建一个名为 SQLServer OLE DB连接来连接到SQL Server实例,如截图# 2 所示。

  4. 在包中创建4个变量,如截图# 3 所示。

  5. 在控制流中,放置一个执行SQL任务,一个 Foreach循环容器 c code code> c $ c> Foreach循环容器,如截图# 4

  6. Confi确定执行SQL任务,如屏幕截图# 5 和# 6 所示。

  7. 配置 Foreach循环容器,如屏幕截图# 7 和# 8 所示。

  8. 将脚本任务中的Main方法替换为脚本任务代码下的代码。

  9. 屏幕截图# 9 显示包执行。

  10. 截图# 10 - # 12 显示从SSIS导出的文件使用脚本任务代码。

希望有所帮助。



SQL脚本:

  CREATE TABLE [dbo]。[Source1](
[Id] [int ] IDENTITY(1,1)NOT NULL,
[ItemNumber] [varchar](20)NOT NULL,
[ItemName] [varchar](50)NOT NULL,
CONSTRAINT [PK_Source1]主要集合([Id] ASC))ON [PRIMARY]
GO

CREATE TABLE [dbo]。[Source2](
[Id] [int] IDENTITY(1,1)NOT NULL,
[Country] [varchar](20)NOT NULL,
[StateProvince] [varchar](50)NOT NULL,
CONSTRAINT [PK_Source2] PRIMARY KEY CLUSTERED([Id] ASC))ON [PRIMARY]
GO

CREATE TABLE [dbo]。[TablesList](
[Id] [int] IDENTITY(1, 1)NOT NULL,
[TableName] [varchar](50)NOT NULL,
[FilePath] [varchar](255)NOT NULL,
CONSTRAINT [PK_Tables] PRIMARY KEY CLUSTERED Id] ASC))ON [PRIMARY]
GO

脚本任务代码: (使用下面给出的代码替换您的脚本任务中的Main()方法)



VB Main()方法代码可用于 SSIS 2005及以上

  public Sub Main()

Dim varCollection As Variables = Nothing

Dts.VariableDispenser.LockForRead(User :: TableName)
Dts。 VariableDispenser.LockForRead(User :: FileName)
Dts.VariableDispenser.LockF orRead(User :: Delimiter)
Dts.VariableDispenser.GetVariables(varCollection)

Dim fileName As String = varCollection(User :: FileName)Value.ToString()
Dim query As String =SELECT * FROM& varCollection(User :: TableName)Value.ToString()
Dim delimiter As String = varCollection(User :: Delimiter)Value.ToString()

Dim writer As StreamWriter = Nothing
Dim connection As OleDbConnection = New OleDbConnection(Dts.Connections(SQLServer)。ConnectionString)
Dim命令As OleDbCommand = Nothing
Dim reader As OleDbDataReader = Nothing

尝试
如果File.Exists(fileName)然后
File.Delete(fileName)
如果

connection.Open()
command = New OleDbCommand(query,connection)
reader = command.ExecuteReader()

如果reader.HasRows然后

writer = New System.IO.StreamWriter( fileName)
Dim row As Integer = 0
While reader.Read()

Dim header As Integer = 0
Dim counter As Integer = 0
Dim fieldCount As Integer = read er.FieldCount - 1

如果row = 0然后
标题< = fieldCount
如果标题<> fieldCount然后
writer.Write(reader.GetName(header).ToString()& delimiter)
Else
writer.WriteLine(reader.GetName(header).ToString())
结束如果
标题+ = 1
结束而
结束如果

当计数器如果计数器& fieldCount然后
writer.Write(reader(counter).ToString()& delimiter)
Else
writer.WriteLine(reader(counter).ToString())
End If
计数器+ = 1
结束虽然

行+ = 1
结束虽然
结束如果
捕获ex作为例外
抛出ex
最后
connection.Close()
writer.Close()
结束尝试

Dts.TaskResult = ScriptResults.Success

End Sub

截图#1:





截图#2:





截图#3:





截图#4:





截图5:





截图#6:





截图#7:





截图#8:





截图#9:





截图#10:





截图#11: / p>



截图#12:




I am trying to create a datagrid and export the contents to a text file using VB.NET and I am doing this inside an SSIS script task in order to automate the process to export a dynamic table to text file. I don't get any error and the files are created but the files are empty.

What am I doing wrong here in this code?

Public Sub Main()

    Dim FName As String = "D:\test.TXT"

    ''''''''''''''''''''''''''''''''''''''''''
    If File.Exists(FName) Then
        File.Delete(FName)
    End If
    ''''''''''''''''''''''''''''''''''''''''''

    Dim myConnection As OleDbConnection = New OleDbConnection("Data Source=localhost;Provider=SQLNCLI10;Initial Catalog=AdventureWorksDW2008R2;Integrated Security=SSPI;")
    Dim da As OleDbDataAdapter = New OleDbDataAdapter("Select * from Table")
    Dim ds As DataSet = New DataSet

    da.Fill(ds, "Test")

    Dim DataGrid1 As New DataGrid
    DataGrid1.DataSource = ds.DefaultViewManager
    Dim DataGridView1 As New DataGridView

    DataGridView1.DataSource = ds

    Dim dgvc As DataGridViewCell
    Dim sw As New System.IO.StreamWriter(FName)

    For Each dgvr As DataGridViewRow In DataGridView1.Rows

        Dim intCellCount As Integer = dgvr.Cells.Count
        Dim intCounter As Integer = 1

        For Each dgvc In dgvr.Cells()
            If intCounter <> intCellCount Then
                sw.Write(dgvc.Value.ToString & "|")
            Else
                sw.WriteLine(dgvc.Value.ToString)
            End If

            intCounter += 1
        Next
    Next

    Dts.TaskResult = ScriptResults.Success

End Sub
解决方案

Here is a possible way of exporting the tables of different structure to flat file using Script Task. This example will export two tables containing different fields and data to a flat file using Script Task. In order to export the data, you can use the DataReader instead of using the DataGrid. There could be other possible ways to do this.

Step-by-step process:

  1. Create three tables named dbo.TablesList, dbo.Source1 and dbo.Source2 using the scripts given under SQL Scripts section.
  2. Populate the tables dbo.TablesList, dbo.Source1 and `dbo.Source2`` with data shown in screenshot #1.
  3. On the SSIS package's Connection manager, create an OLE DB connection named SQLServer to connect to the SQL Server instance as shown in screenshot #2.
  4. In the package, create 4 variables as shown in screenshot #3.
  5. In the Control Flow, place an Execute SQL Task, a Foreach Loop Container and a Script Task within the Foreach loop container as shown in screenshot #4.
  6. Configure the Execute SQL task as shown in screenshots #5 and #6.
  7. Configure the Foreach Loop container as shown in screenshots #7 and #8.
  8. Replace the Main method inside the Script Task with the code given under the section Script Task Code.
  9. Screenshot #9 shows package execution.
  10. Screenshots #10 - #12 show the files exported from SSIS using Script Task code.

Hope that helps.

SQL Scripts:

CREATE TABLE [dbo].[Source1](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [ItemNumber] [varchar](20) NOT NULL,
    [ItemName] [varchar](50) NOT NULL,
CONSTRAINT [PK_Source1] PRIMARY KEY CLUSTERED ([Id] ASC)) ON [PRIMARY]
GO

CREATE TABLE [dbo].[Source2](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Country] [varchar](20) NOT NULL,
    [StateProvince] [varchar](50) NOT NULL,
CONSTRAINT [PK_Source2] PRIMARY KEY CLUSTERED ([Id] ASC)) ON [PRIMARY]
GO

CREATE TABLE [dbo].[TablesList](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [TableName] [varchar](50) NOT NULL,
    [FilePath] [varchar](255) NOT NULL,
CONSTRAINT [PK_Tables] PRIMARY KEY CLUSTERED ([Id] ASC)) ON [PRIMARY]
GO

Script Task Code: (Use the code given below to replace the Main() method in your Script task)

VB Main() method code that can be used in SSIS 2005 and above:

Public Sub Main()

    Dim varCollection As Variables = Nothing

    Dts.VariableDispenser.LockForRead("User::TableName")
    Dts.VariableDispenser.LockForRead("User::FileName")
    Dts.VariableDispenser.LockForRead("User::Delimiter")
    Dts.VariableDispenser.GetVariables(varCollection)

    Dim fileName As String = varCollection("User::FileName").Value.ToString()
    Dim query As String = "SELECT * FROM " & varCollection("User::TableName").Value.ToString()
    Dim delimiter As String = varCollection("User::Delimiter").Value.ToString()

    Dim writer As StreamWriter = Nothing
    Dim connection As OleDbConnection = New OleDbConnection(Dts.Connections("SQLServer").ConnectionString)
    Dim command As OleDbCommand = Nothing
    Dim reader As OleDbDataReader = Nothing

    Try
        If File.Exists(fileName) Then
            File.Delete(fileName)
        End If

        connection.Open()
        command = New OleDbCommand(query, connection)
        reader = command.ExecuteReader()

        If reader.HasRows Then

            writer = New System.IO.StreamWriter(fileName)
            Dim row As Integer = 0
            While reader.Read()

                Dim header As Integer = 0
                Dim counter As Integer = 0
                Dim fieldCount As Integer = reader.FieldCount - 1

                If row = 0 Then
                    While header <= fieldCount
                        If header <> fieldCount Then
                            writer.Write(reader.GetName(header).ToString() & delimiter)
                        Else
                            writer.WriteLine(reader.GetName(header).ToString())
                        End If
                        header += 1
                    End While
                End If

                While counter <= fieldCount
                    If counter <> fieldCount Then
                        writer.Write(reader(counter).ToString() & delimiter)
                    Else
                        writer.WriteLine(reader(counter).ToString())
                    End If
                    counter += 1
                End While

                row += 1
            End While
        End If
    Catch ex As Exception
        Throw ex
    Finally
        connection.Close()
        writer.Close()
    End Try

    Dts.TaskResult = ScriptResults.Success

End Sub

Screenshot #1:

Screenshot #2:

Screenshot #3:

Screenshot #4:

Screenshot #5:

Screenshot #6:

Screenshot #7:

Screenshot #8:

Screenshot #9:

Screenshot #10:

Screenshot #11:

Screenshot #12:

这篇关于使用SSIS脚本任务将数据从多个SQL表导出到不同的平面文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 00:13