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 theDataReaderinstead of using theDataGrid. There could be other possible ways to do this.Step-by-step process:
dbo.TablesList,dbo.Source1anddbo.Source2using the scripts given under SQL Scripts section.dbo.TablesList,dbo.Source1and `dbo.Source2“ with data shown in screenshot #1.Connection manager, create anOLE DB connectionnamed SQLServer to connect to the SQL Server instance as shown in screenshot #2.Execute SQL Task, aForeach Loop Containerand aScript Taskwithin theForeach loop containeras shown in screenshot #4.Execute SQL taskas shown in screenshots #5 and #6.Foreach Loop containeras shown in screenshots #7 and #8.Script Task Code.Hope that helps.
SQL Scripts:
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:Screenshot #1:
Screenshot #2:
Screenshot #3:
Screenshot #4:
Screenshot #5:
Screenshot #6:
Screenshot #7:
Screenshot #8:
Screenshot #9:
Screenshot #10:
Screenshot #11:
Screenshot #12: