I’m streaming data from a CSV file and trying to import it to SQL Server 2008. I’ve looked around on the web and I’ve come up with this approach , which is not working. Any ideas on how to make it better (in the sense that it actually works).
The input parameter is the CSV data in a DataTable.
Here’s the code:
private void ExportCSV(DataTable dtCSV)
{
DateTime dayOfYear = DateTime.Now.Date;
dtCSV.TableName = "ActivationDate_"+dayOfYear.ToString();
string createTempTable = "SELECT * INTO ThisActivation FROM @tvp";
using (SqlDataAdapter adap = new SqlDataAdapter(createTempTable,GetConnection()))
{
adap.InsertCommand.Parameters.Add("@tvp", SqlDbType.NVarChar, int.MaxValue);
adap.InsertCommand.Parameters["@tvp"].Value = dtCSV;
adap.InsertCommand.ExecuteNonQuery();
}
}
You can’t parameterize table names (or column names, for that matter).
One option it to revert to dynamic SQL, though that opens you up to SQL injection.
This will work, though you should be very careful to validate
dtCSVto avoid SQL injection.