C# SQL BulkCopy class create SQL table if not there

Hi
       I use the following code to upload data from a data table to a SQL table calling the Bulk Copy class
       If the SQL table is not there then I want to automatically create it. How do I update my code
      to do this?


     DataTable tableDataTable = oDataSet.Tables[0];

            string conString = "Server = localhost; Database = Test1; Trusted_Connection = Yes;";
            using (SqlConnection con = new SqlConnection(conString))
            {

                using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
                {
                    Create_Table();
                    sqlBulkCopy.DestinationTableName = "MTEST";
                    sqlBulkCopy.BulkCopyTimeout = 0;
                    //Indefinite when zero

                    con.Open();
                    sqlBulkCopy.WriteToServer(tableDataTable);
                    con.Close();
                }
            }
Murray BrownMicrosoft Cloud Azure/Excel Solution DeveloperAsked:
Who is Participating?
 
Duy PhamFreelance IT ConsultantCommented:
You need to check existence of destination table manually, and create it if it doesn't exist.

If destination table is on the same database as source table, you don't need SqlBulkCopy, just do:

SELECT * INTO [destinationTable] FROM [sourceTable]

Open in new window


Or you can check out Ronald Rosier's solution, in which he does format a CREATE TABLE command for creating destination table based on the schema of source table. And then use SqlBulkCopy afterwards.
0
 
Vitor MontalvãoMSSQL Senior EngineerCommented:
What the Create_Table() does?
0
 
Murray BrownMicrosoft Cloud Azure/Excel Solution DeveloperAuthor Commented:
That is code to create a table using a SQL statement that I used to test alternatives. Please ignore it in this post
0
 
Vitor MontalvãoMSSQL Senior EngineerCommented:
The SELECT INTO presented above by Duy should do the trick. It will create the table if doesn't exist. Otherwise will append data on it.
0
 
Murray BrownMicrosoft Cloud Azure/Excel Solution DeveloperAuthor Commented:
Thank you both
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.