ExecuteNonQuery()具有日期插入的异常

时间:2013-06-19 22:18:46

标签: c# sql sql-server tsql ado.net

我有一个存储过程来插入记录并返回插入记录的ID。

这是我的SQL实现:

ALTER PROCEDURE InsertViolation 
    @FactoryName nvarchar(50) ,
    @Type  nvarchar(100),
    @Location nvarchar(30) ,
    @Desc nvarchar(300),
    @Severity nvarchar(300),
    @DateObserved datetime,
    @ViolationNumber bigint output
AS
BEGIN
    SET NOCOUNT ON;

INSERT INTO Violation
       (Violation_Factory_Name
       ,Violation_Type
       ,Violation_Location
       ,Violation_Desc
       ,Violation_Severity
       ,Violation_Date_Observed)
 VALUES
       (@FactoryName
       ,@Type
       ,@Location
       ,@Desc
       ,@Severity
       ,@DateObserved)
SET @ViolationNumber=SCOPE_IDENTITY()
      RETURN  @ViolationNumber
END

我有这个C#代码来调用这个过程:

 public static long Insert_Violation(Model.Violation violation)
 {
        string strStoredProcedureName = "InsertViolation";
        SqlCommand cmd = new SqlCommand(strStoredProcedureName);
        string strConnString = ConfigurationManager.ConnectionStrings["ViolationConnection"].ConnectionString;

        SqlConnection con = new SqlConnection(strConnString);
        cmd.Connection = con;
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@FactoryName", violation.FactoryName);
        cmd.Parameters.AddWithValue("@Type", violation.ViolationType);
        cmd.Parameters.AddWithValue("@Location", violation.Location);
        cmd.Parameters.AddWithValue("@Desc", violation.ViolationDesc);
        cmd.Parameters.AddWithValue("@Severity", violation.Serverity);
        cmd.Parameters.AddWithValue("@DateObserved", violation.DateObserved);
        cmd.Parameters.AddWithValue("@ViolationNumber", -1).Direction = ParameterDirection.Output;

        try
        {
            con.Open();
            cmd.ExecuteNonQuery();

            return (long) cmd.Parameters["@ViolationNumber"].Value;

        }
        catch(Exception ex)
        {
            throw new Exception(ex.Message + " Date Parameter value is " + cmd.Parameters["@DateObserved"].Value + " \n DateTime Object converted to string value is " + violation.DateObserved.ToString());
            return -1;
        }
        finally
        {
            con.Dispose();
            cmd.Dispose();
        }
    }

我发现该行已插入数据库但在cmd.ExecuteNonQuery();引发了异常,问题是我使用的是violation.DateObserved C#DateTime对象和相应的参数, DB中的字段的类型为datetime

这是捕获的异常消息,我使用throw异常来打印它:

  

System.Exception:指定的强制转换无效。日期参数值为15/12/2012 12:00:00   DateTime对象转换为字符串值为15/12/2012 12:00:00

所以我无法得到记录号,而我的函数在访问catch时返回-1。

1 个答案:

答案 0 :(得分:1)

return语句隐式地将结果强制转换为整数;因此,您应该取消int,而不是long

return (int) cmd.Parameters["@ViolationNumber"].Value;

如果您拥有的值不适合int,则使用out参数或select值并使用ExecuteScalar