I am trying to insert today’s date and try increment the date recursively. but I am getting conversion error message.
private void InsertTimesheetWeek(string timeSheetID)
{
int row = GViewTimeSheet.Rows.Count;//get the row count
int counter = 0;
string[] txtDate = new string[row];// date column
foreach (GridViewRow gRow in GViewTimeSheet.Rows)
{
txtDate[counter] = "GetDATE()+"+counter;
counter++;
}
//Intializing sql statement
string fields = "(TimeSheetID, Date)";
string parm = "(@TimeSheetID, @Date)";
string sqlStatement = "insert into TimeSheetWeeks" + fields + "Values" + parm;
SqlCommand comm = new SqlCommand();
comm.CommandText = sqlStatement;//assing sql statement as command
SqlConnection connection = DataAccess.getConnection();
comm.Connection = connection;
try
{
connection.Open();
for (int i = 0; i < row; i++)
{
comm.Parameters.AddWithValue("@TimeSheetID", timeSheetID);
comm.Parameters.AddWithValue("@Date", txtDate[i]);
comm.ExecuteNonQuery();
comm.Parameters.Clear();
}
}
catch (Exception ex)
{
Utilities.LogError(ex);
throw ex;
}
finally
{
if (connection.State == ConnectionState.Open)// if the connection opened then
{
connection.Close();//just close the connection in any way
}
}
}
Why it causes an error?
The error is caused by passing “GetDATE()+1”, “GetDATE()+2”, etc. as a parameter and SQL can’t convert this to a date.
Do the date calculations in code before sending to SQL:
The approach you’ve taken would work if you were building the SQL statement as a literal for each row.
ex:*
*N.B. Don’t use the above code – I’ve provided it as an example only. Always use SQL parameters if possible. Parameters are type-safe and mitigate the risk of SQL injection. How To: Protect From SQL Injection in ASP.NET