Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi guys,
I have a .CSV file with this content:
1732,Juan Perez,435.00,11-05-2002
554,Pedro Gomez,12342.30,06-02-2004
112,Ramiro Politti,0.00,01-02-2000
924,Pablo Ramirez,3321.30,24-11-2002
I have managed to read and insert all the records into a DataTable in C#, now I need to generate a TSQL INSERT script for this table along with the DATA in it.
any suggestions?
Posted

SO here is what you need to do;

You can do it one row at a time in to the database.

Mainly this method is just opening a connection to the access db, going through each row in the gridview datasource (if you create the datasource on the fly you might need to recreate the table at the beginning instead of pulling it from the gridview) and then pushing each row in to the table via an insert command in SQL.

Retrieve data
C++
DataTable dtTable = Gridview1.datasource;


Create a connection string
string connString ="";
Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;


Open a connection
C++
SqlConnection cnx = new SqlConnection(connString);


To read each row in datatable a reiteration method
For Each iRow as Datarow in dtTable

Specify the SQL string
MIDL
string strSQL = "INSERT INTO
TestTable(Col1,Col2) VALUES (" + iRow.item("Col1") + "," + iRow.item("Col1") + ")";

'Create a command object
C++
SqlCommand cmd = new SqlCommand();
            cmd.CommandText = strSQL;
            cmd.Connection = cnx;

'Execute Insert
C#
try
            {
                cnx.Open();
                cmd.ExecuteNonQuery();
            }



'Close the db connection
cnx.Close()

Or instead you can do a BULK Insert. By using SQLBulkCopy Class[^]
 
Share this answer
 
v3
Comments
Sandeep Mewara 8-Mar-11 3:28am    
Good answer. 5!
If you fetched all records into datatable the directly pass this datatable into a stored procedure and from stored procedure insert all rows into one shot by insert select query.

Please let me know if you want this solution.

Remeber this works only in sql server 2008 onwards.

but

If you have CSV file use bulk copy.

with line seperator as \n and field seperator as ,

Remaining is upto your requirement.
 
Share this answer
 
v2
i have same query how to convert select and insert query in script and save in dynamic table ob single click event
 
Share this answer
 

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