Reputation: 666
I have a problem inserting a datetime format variable to Sql Server 2005 database. DateTime Format is dd.MM.yyyy
conn.Open();
string conString = "SET DATEFORMAT DMY INSERT INTO AmortPlanT (InvestmentID,StartDate,Maturity,IRate,CoupPerYear,parValue) Values (@IIndex,'@StartDate','@Maturity',@IRate,@CouponPerYear,@parValue)";
using (SqlCommand myCommand = new SqlCommand(conString, conn))
{
myCommand.CommandType = CommandType.Text;
myCommand.Parameters.Add("@IIndex", SqlDbType.Int).Value = investmentIndex;
myCommand.Parameters.Add("@StartDate", SqlDbType.DateTime).Value = startDate;
myCommand.Parameters.Add("@Maturity", SqlDbType.DateTime).Value = maturity;
myCommand.Parameters.Add("@IRate", SqlDbType.Float).Value = iRate;
myCommand.Parameters.Add("@CouponPerYear", SqlDbType.Int).Value = coupPerYear;
myCommand.Parameters.Add("@parValue", SqlDbType.Float).Value = parValue;
myCommand.ExecuteNonQuery();
}
StartDate and Maturity are DateTime variables i get from dateTimePicker.Value .
And i'm always getting the error:
Conversion failed when converting datetime from character string.
Thank you for your help.
Upvotes: 1
Views: 2187
Reputation: 1062492
The problem is that you are thinking in terms of strings...
DateTime Format is dd.MM.yyyy
No, it isn't; the format of a DateTime
(when passed as a parameter) is really just a number as binary ;-p (startDate
should be a DateTime
- not a string
).
When you are using parameters, you don't include the string tokens ('
) - otherwise you mean "the string '@name'
", rather than "the string held in parameter @name
"; try removing them:
string conString = @"
SET DATEFORMAT DMY INSERT INTO AmortPlanT (InvestmentID,StartDate,Maturity,IRate,CoupPerYear,parValue)
VALUES (@IIndex,@StartDate,@Maturity,@IRate,@CouponPerYear,@parValue)";
Upvotes: 1
Reputation: 39916
You are not supposed to put your parameters in quotes.. here is the correct query..
'@StartDate' in values clause is wrong, it should be just @StartDate... as explained below...
conn.Open();
string conString = "SET DATEFORMAT DMY INSERT INTO AmortPlanT
(InvestmentID,StartDate,Maturity,IRate,CoupPerYear,parValue) Values
(@IIndex,@StartDate,@Maturity,@IRate,@CouponPerYear,@parValue)";
using (SqlCommand myCommand = new SqlCommand(conString, conn))
{
myCommand.CommandType = CommandType.Text;
myCommand.Parameters.Add("@IIndex", SqlDbType.Int).Value = investmentIndex;
myCommand.Parameters.Add("@StartDate", SqlDbType.DateTime).Value = startDate;
myCommand.Parameters.Add("@Maturity", SqlDbType.DateTime).Value = maturity;
myCommand.Parameters.Add("@IRate", SqlDbType.Float).Value = iRate; myCommand.Parameters.Add("@CouponPerYear", SqlDbType.Int).Value = coupPerYear;
myCommand.Parameters.Add("@parValue", SqlDbType.Float).Value = parValue; myCommand.ExecuteNonQuery();
}
Upvotes: 2