giovedì 31 ottobre 2013

C# - SqlBulkCopy

SqlBulkCopy lets you efficiently bulk load a SQL Server table with data from another source.
For example if you need to synchronize differente Sql Server Tables or to put data from DataTable (or DataSource) to Sql Server Table in a very efficient way.

Here a Little Example:



public void UpdateTable(SqlConnection con, SqlTransaction tra, DataSet ds, string table)
        {
            string sql = "DELETE FROM " + table;

            SqlCommand com = new SqlCommand();
            com.Connection = con;
            com.CommandText = sql;

            if (tra != null)
                com.Transaction = tra;

            com.ExecuteNonQuery();

            SqlCommand Command = new SqlCommand();
            Command.Connection = con;
            if (tra != null)
                Command.Transaction = tra;

            SqlBulkCopy copy = new SqlBulkCopy(con, SqlBulkCopyOptions.Default, tra);
            copy.DestinationTableName = table;
            copy.WriteToServer(ds.Tables[0]);
        }

with this cose, you can copy data from a ds to Sql Server Table. 

My Two Cents ...  

Nessun commento:

Posta un commento