-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBulkUpdate.cs
75 lines (64 loc) · 2.39 KB
/
BulkUpdate.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
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace BulkOperations
{
public static class BulkUpdate
{
public const string TempTableName = "#Customer";
public const string TableName = "Customer";
public const string CreateTempTable =
"select * into #Customer from Customer";
public const string UpdateTable =
@"
update Customer
set
Customer.FirstName = #Customer.FirstName,
Customer.LastName = #Customer.LastName,
Customer.DateOfBirth = #Customer.CreatedAt,
Customer.CreatedAt = #Customer.DateOfBirth
from #Customer
";
public const string DropTempTable =
"drop table #Customer;";
public static void UpdateData<T>(List<T> list)
{
var dataTable = new DataTable(TempTableName);
dataTable.FromList(list);
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
using (var connection = new SqlConnection())
{
connection.Configure();
using (var command = new SqlCommand("", connection))
{
try
{
connection.Open();
command.CommandText = CreateTempTable;
command.ExecuteNonQuery();
using (var bulkcopy = new SqlBulkCopy(connection))
{
bulkcopy.BulkCopyTimeout = 660;
bulkcopy.DestinationTableName = TableName;
bulkcopy.WriteToServer(dataTable);
bulkcopy.Close();
}
command.CommandTimeout = 300;
command.CommandText = $"{UpdateTable}{DropTempTable}";
command.ExecuteNonQuery();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
connection.Close();
}
}
}
}
}
}