-
Notifications
You must be signed in to change notification settings - Fork 1
/
Program.cs
106 lines (90 loc) · 3.28 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
using CsvHelper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace DataTransfer.SqlToCsv
{
class Program
{
private const string _schema = "dbo";
private const string _table = "<YOURTABLENAME>";
private const string _sqlConnectionString = "<YOURSQLCONNECTIONSTRING>";
private const string _outputPath = "<PATHTOYOURLOCALFILE>";
static int Main(string[] args)
{
try
{
// Start!
MainAsync(args).Wait();
return 0;
}
catch
{
return 1;
}
}
static async Task MainAsync(string[] args)
{
using (var streamWriter = new StreamWriter(_outputPath))
using (var csvWriter = new CsvWriter(streamWriter))
{
// Quote all fields
csvWriter.Configuration.ShouldQuote = (field, context) => true;
bool writeHeaders = true;
await foreach (DataRow row in GetSqlRowsAsync(_schema, _table))
{
// Write header row
if (writeHeaders)
{
foreach (DataColumn column in row.Table.Columns)
{
csvWriter.WriteField(column.ColumnName);
}
await csvWriter.NextRecordAsync();
writeHeaders = false;
}
// Write data rows
for (var i = 0; i < row.ItemArray.Length; i++)
{
csvWriter.WriteField(row[i]);
}
await csvWriter.NextRecordAsync();
}
}
}
public static async IAsyncEnumerable<DataRow> GetSqlRowsAsync(string schema, string tableName)
{
SqlConnection _sqlConnection = new SqlConnection(_sqlConnectionString);
using (SqlCommand command = new SqlCommand("select * from " + schema + "." + tableName))
{
command.Connection = _sqlConnection;
await _sqlConnection.OpenAsync();
DataTable table = new DataTable();
// Get schema of SQL table
using (SqlDataAdapter adapter = new SqlDataAdapter(command))
{
table.TableName = tableName;
adapter.FillSchema(table, SchemaType.Source);
}
// Return rows as they're read
using (SqlDataReader reader = await command.ExecuteReaderAsync())
{
while (await reader.ReadAsync())
{
DataRow row = table.NewRow();
row.Table.Columns
.Cast<DataColumn>()
.ToList()
.ForEach(x => row[x] = reader.GetValue(x.Ordinal));
yield return row;
}
}
_sqlConnection.Close();
}
}
}
}