2009-08-16 34 views
1

SQL Server 2005データベースにdatetime形式の変数を挿入するときに問題があります。 DateTime型の書式がDD.MM.YYYYSql Server 2005にDateTimeを挿入する

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(); 

       } 

開始日と成熟度は私がdateTimePicker.Valueから取得したDateTime変数ですされています。

と私は常にエラーを取得しています:文字列からdatetime型に変換するとき

変換に失敗しました。

ありがとうございました。以下に説明するよう

答えて

2

あなたはここに正しいクエリ..

は..です引用符であなたのパラメータを置くことになっていません "@StartDateの価値観に句が間違っている、それは...ただ@StartDateでなければなりません。 ..

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();     
} 
1

問題はありません、それはない...あなたは、文字列の面で考えていることを

DateTime Format is dd.MM.yyyy

です。 DateTime(パラメータとして渡される場合)の形式は実際にはバイナリ; -p(startDateDateTimeでなければならず、stringでなくてはなりません)という数字です。あなたはパラメータを使用している

するときは、文字列トークン(')が含まれていない - そうでなければ、むしろ「パラメータ@nameで開催された文字列」よりも「文字列'@name'」を意味します。それらを削除してみてください:

string conString = @" 
SET DATEFORMAT DMY INSERT INTO AmortPlanT (InvestmentID,StartDate,Maturity,IRate,CoupPerYear,parValue) 
VALUES (@IIndex,@StartDate,@Maturity,@IRate,@CouponPerYear,@parValue)"; 
関連する問題