Saturday, August 27, 2011

Copying data from data table to sql server table using bulk copy

using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Xml.Linq;
using System.Data.SqlClient;
using Microsoft.SqlServer.Management.Common;//add these references to ur project
using Microsoft.SqlServer.Management.Smo;


    public class ExcelToTable
    {
        #region Bulk Copy

        public void BulkCopy(DataTable dtDataCopy, bool CreateTable, string TableName)
        {
            string conString = ConfigurationManager.ConnectionStrings["ConString"].ToString();
            SqlConnection con = new SqlConnection(conString);
            try
            {
                if (con.State == ConnectionState.Closed)
                    con.Open();
                Server server = new Server(new ServerConnection(con));
                Table tbl = new Table(server.Databases[server.ConnectionContext.DatabaseName], TableName);
                if (CreateTable)
                {
                    if (server.Databases[server.ConnectionContext.DatabaseName].Tables[TableName] != null)
                        server.Databases[server.ConnectionContext.DatabaseName].Tables[TableName].Drop();

                    Column colTemp = new Column();
                    foreach (DataColumn dc in dtDataCopy.Columns)
                    {
                        colTemp = new Column(tbl, dc.ColumnName.ToString());
                        colTemp.DataType = Microsoft.SqlServer.Management.Smo.DataType.VarChar(300);
                        colTemp.Nullable = true;
                        tbl.Columns.Add(colTemp);
                    }
                    tbl.Create();
                }
                else
                {

                    //Delete the from the table or performig other actions
                }
                if (con.State == ConnectionState.Open)
                    con.Close();
                con = new SqlConnection(conString);
                if (con.State == ConnectionState.Closed)
                    con.Open();
                SqlBulkCopy copy = new SqlBulkCopy(con);

                foreach (DataColumn dc in dtDataCopy.Columns)
                {
                    copy.ColumnMappings.Add(dc.ColumnName, dc.ColumnName);
                }
                copy.DestinationTableName = TableName;
                copy.WriteToServer(dtDataCopy);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {

                con.Close();
            }
        }

        #endregion
    }

No comments:

Post a Comment