Live with Dot Net Just another Programming weblog

SQL Bulk Copy using SQL Server 2005

Posted on December 16, 2011

The below code help in copying a large amount of data from the local datastore to the sql server database.

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
protected void Button11_Click(object sender, EventArgs e) 
{ 
ConnectionStringSettings pubs =    ConfigurationManager.ConnectionStrings["PubsData"]; 
DbConnection connection =    new SqlConnection(pubs.ConnectionString); ConnectionStringSettings bulkCopy =    ConfigurationManager.ConnectionStrings["PubsData"]; 
SqlConnection bulkCopyConnection =   new SqlConnection(bulkCopy.ConnectionString); 
DbCommand cmd = connection.CreateCommand(); 
cmd.CommandType = CommandType.Text; 
cmd.CommandText = "SELECT stor_name FROM Stores"; 
connection.Open(); 
bulkCopyConnection.Open();
 
//make sure that table exists and is empty
//in case button is clicked more that once
SqlCommand cleanup = bulkCopyConnection.CreateCommand(); 
cleanup.CommandText =    "IF EXISTS ( SELECT * FROM sys.objects " + " WHERE object_id = OBJECT_ID('dbo.StoreList') " + " AND type in ('U')) " + "DROP TABLE dbo.StoreList " + "CREATE TABLE dbo.StoreList(stor_name varchar(40) NOT NULL )"; 
cleanup.ExecuteNonQuery();
 
//do the bulkcopy
DbDataReader rdr = cmd.ExecuteReader(); 
SqlBulkCopy bc = new SqlBulkCopy(bulkCopyConnection); 
bc.DestinationTableName = "StoreList";
bc.WriteToServer(rdr); 
connection.Close(); 
bulkCopyConnection.Close(); 
Label lbl = GetLabel(275, 20);
lbl.Text = "Done with bulk copy"; 
}

About admin

No description. Please complete your profile.
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


ERROR: That reCAPTCHA response was incorrect.

 

No trackbacks yet.