Click here to Skip to main content
15,913,941 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
How to insert a data table into SQL Server database table ?
Posted
Updated 11-Sep-16 8:09am
Comments
Maciej Los 17-Dec-13 4:21am    
What have you done till now? Where are you stuck?
Praveen_P 17-Dec-13 4:26am    
i retrieved values from 3 tables using join query , now my datatable contains this value now i need to store it in another database table..

dt is data table

C#
for (int i = 0; dt.Rows.Count > i; i++)
            {
                //insert Query
            }


insert query like

C#
insert into tableName values ( dt.Rows[i].ItemArray.GetValue(0).ToString(), dt.Rows[i].ItemArray.GetValue(1).ToString(), dt.Rows[i].ItemArray.GetValue(2).ToString() etc...)


i hope this code helps a bit...
 
Share this answer
 
Comments
Member 14883666 21-Jul-20 2:44am    
What if non string data type?
You may try the SqlBulkCopy without looping:
SqlBulkCopy
SqlBulkCopy class
 
Share this answer
 
v2
Comments
Praveen_P 17-Dec-13 5:49am    
thanks , its working smoothly
Kedar Kulkarni 26-Jul-14 1:28am    
Any suggestions as to how can i modify it in a stored procedure ??
Hi Praveen,

If you are using SQL Server 2008 then its easy to do using Table object and Store procedure.
You can refer here[^] for samples.
Here[^] is how you can implement.

Hope this helps you a bit.

Regards,
RK
 
Share this answer
 
Comments
Praveen_P 17-Dec-13 5:48am    
thank u
C#
DataTable dt = new DataTable();
    dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)),
                        new DataColumn("Name", typeof(string)),
                        new DataColumn("Country",typeof(string)) });
    foreach (GridViewRow row in GridView1.Rows)
    {
        if ((row.FindControl("CheckBox1") as CheckBox).Checked)
        {
            int id = int.Parse(row.Cells[1].Text);
            string name = row.Cells[2].Text;
            string country = row.Cells[3].Text;
            dt.Rows.Add(id, name, country);
        }
    }
    if (dt.Rows.Count > 0)
    {
        string consString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(consString))
        {
            using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
            {
                //Set the database table name
                sqlBulkCopy.DestinationTableName = "dbo.Customers";
 
                //[OPTIONAL]: Map the DataTable columns with that of the database table
                sqlBulkCopy.ColumnMappings.Add("Id", "CustomerId");
                sqlBulkCopy.ColumnMappings.Add("Name", "Name");
                sqlBulkCopy.ColumnMappings.Add("Country", "Country");
                con.Open();
                sqlBulkCopy.WriteToServer(dt);
                con.Close();
            }
        }
    }
 
Share this answer
 
v2
Write in Stored Procedure Table name eg: MoodleUsersTable
SQL
use Sample
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<m.nabeel siddiqui="">
-- Create date: <19/4/2016>
-- Description:	<adding records="" in="" moodleusers="">
-- =============================================
Alter PROCEDURE InsertMoodleUsers
@MoodleUserTable MoodleUsersTable readonly

AS
BEGIN
insert into MoodleUsers select * from @MoodleUserTable
END
GO</adding></m.nabeel>


and c# code here

C#
public void runsp(DataTable dt1,string spName)
        {
            SqlCommand cmd = new SqlCommand(spName, connection);
            cmd.CommandType = CommandType.StoredProcedure;
            SqlParameter dtparam = cmd.Parameters.AddWithValue("@MoodleUserTable", dt1);

            dtparam.SqlDbType = SqlDbType.Structured;
            Start();
            cmd.ExecuteNonQuery();
            Stop();
        }
 
Share this answer
 
Comments
CHill60 19-Apr-16 8:49am    
Question is over 2 years old and already answered.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900