7

Is there anyway to insert in bulk a System.Data.DataTable in C# into a SQL Server table using a store procedure and passing this table as parameter?

The table won't have a fixed number of records.

1
  • 1
    Which version of SQL Server? 2008? Commented Jul 27, 2010 at 9:45

2 Answers 2

8

Yes there is a way:

        DataTable dataTable = null; // your data needs to be here
        try
        {
            ConnectionStringSettings mConString = ConfigurationManager.ConnectionStrings["SiteSqlServer"];

            // Optional truncating old table
            using (SqlConnection connection = new SqlConnection(mConString.ConnectionString))
            {
                connection.Open();
                // Delete old entries
                SqlCommand truncate = new SqlCommand("TRUNCATE TABLE MYTABLE", connection);
                truncate.ExecuteNonQuery();
            }

            SqlBulkCopy bulkCopy = new SqlBulkCopy(mConString.ConnectionString, SqlBulkCopyOptions.TableLock)
                                          {
                                              DestinationTableName = "dbo.MYTABLE",
                                              BatchSize = 100000,
                                              BulkCopyTimeout = 360
                                          };
            bulkCopy.WriteToServer(dataTable);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }

Please experiement with the BatchSize - 100000 was good for me - it should not be larger than that - speed migth decrease otherwise. BatchSize does not limit your data - it's just the size of each "packet" that will be sent to the sql server.

SiteSQLServer should be inside your app.config or web.config. You need to change the parameters here if not.

Please change MYTABLE to your table name.

Sign up to request clarification or add additional context in comments.

3 Comments

Andread, that works fine but what if you have a stubborn DBA who does not give Bulk Insert Permissions..??? then what
This would not work. But this was not the question... Bulk insert should be enabled to use this and this is the default.
@MethodMan you can pass DataTable as stored procedure parameter (user defined table type). But you will lose advantage of EnableStreaming feature of SqlBulkCopy
3

In SQL Server versions before 2008, the only way to push an entire DataTable to SQL Server was SqlBulkCopy. You have to push all data into (probably temporary) staging table and call the procedure to process the staged data.

In SQL Server 2008, table-valued user-defined types have been introduced. They provide some great new options to work with sets of data.

Have a look at MSDN:

and probably a second at two of my blog posts:

6 Comments

Sure, slower (however, not too much) but more powerful, since no staging table needed
hi Florian, Just trying to run something like this but it doesn't work... USE AdventureWorks; GO /* Create a user-defined table type */ CREATE TYPE LocationTableType AS TABLE ( LocationName VARCHAR(50) , CostRate INT ); GO I have the AdventureWorks db in my SQL Server, shouldn't I be able to create the new type? I just get this error... Msg 156, Level 15, State 1, Line 3 Incorrect syntax near the keyword 'AS'. Thanks
Please try: "PRINT @@VERSION;". Does it return SQL Server 2008 or another version? If 2008, check database properties for compatibility mode version "10"
Ok, we are using 2005... so I will have to use the other solution, right? SQLBulkCopy...
So SqlBulkCopy is the best way to go
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.