OLEDB and C# bulk insert for Excel spreadsheet creation
I am using C# to read a SQL stored procedure, put the results of the stored procedure into a C# data table and then reading the data table row by row to build up my "Insert into....values "etc. This creates my Excel spreadsheet with the correct data. However, instead of inserting row by row, is there a way of doing a bulk insert?
Failing that I was thinking of getting the stored procedure to write the results to a permanent table and therefore is there a way of doing an "Insert into ....select from ". When I have tried this in C# the code is unable to find the SQL table name specified "Microsoft database access engine cannot find the object ", what is the correct syntax and where do you specify where/how to access the SQL table?
Thanks
Hi, that link looks like it's using Microsoft.Office.Interop.Excel; I'm using OLEDB (which i'm now beginning to regret!). So basically i have a C# class that is called from another component. This C# class reads a sql stored procedure, puts the results into a data table. I then set up the table definition using the OLEDBcommand "Insert into ( []) values ("?"). I then define the parameters e.g. cmd.Parameters.Add(columnHeading, OleDbType.VarChar, size) etc. Then for each row i find in the data table i set the cmd.Parameters[i].value = row[i], where parameters[i] is incremented for each column in that row. I then loop round for each data row and set cmd.Parameters[i].value ap开发者_运维技巧propriately. As I have to set the cmd.Parameters[i].Value for each row i find in my dataset and then cmd.ExecuteNonQuery(); , this is quite time consuming. So is there a way to bulk insert the data from the data table into the OLEDB command, if not, can i insert the data by referencing a SQL table directly and doing a "insert into..select from"?
You can separate your insert statements with a semicolon and run just 1 command. For instance ...
string sql = "insert into table (col1,col2) values ('row1','row1');"
sql += "insert into table (col1,col2) values ('row2','row2');"
sql += "insert into table (col1,col2) values ('row3','row3');"
SqlConnection conn = new SqlConnection("some connection string");
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
conn.ExecuteNonQuery();
conn.Dispose();
cmd.Dispose();
Or something similar. You are executing all 3 queries with 1 command. This might not work with databases other than SQL Server, but will definitely work with SQL Server.
精彩评论