是否可以将null(“”)值插入数据库中的datetime字段

时间:2013-02-22 06:13:39

标签: c# asp.net sqldatetime

我有两个字段DOB(出生日期)和(加入日期)如果用户在数据库中输入日期  insert-> date else insert-> null

我已将属性定义为

  public DateTime DOB
    {
        get;
        set;
    }
    public DateTime DOJ
    {
        get;
        set;
    }

现在在save_click事件中

        IFormatProvider provider = new System.Globalization.CultureInfo("en-CA", true);
        String datetime = txtDOB.Text.Trim();
        DateTime date = DateTime.Parse(datetime, provider, System.Globalization.DateTimeStyles.NoCurrentDateDefault);
        objEmp.DOB = date;

        provider = new System.Globalization.CultureInfo("en-CA", true);
        datetime = txtDOJ.Text.Trim();
        date = DateTime.Parse(datetime, provider, System.Globalization.DateTimeStyles.NoCurrentDateDefault);
        objEmp.DOJ = date;

class.cs

        param[7] = new Service.SqlParameter();
        param[7].ParameterName = "@DOB";
        param[7].Value = DOB;
        param[7].SqlDbType = Service.SqlDbType.DateTime;

        param[8] = new Service.SqlParameter();
        param[8].ParameterName = "@DOJ";
        param[8].Value = DOJ;
        param[8].SqlDbType = Service.SqlDbType.DateTime;

我希望当用户没有插入任何日期时,应插入null ...但是通过此代码我收到错误 存储过程

@FK_EmployeeTypeID Numeric(18,0),
    @EmployeeName NVARCHAR(50), 
    @CellNo  NVARCHAR(50),  
    @PhNo  NVARCHAR(50),    
    @Address  NVARCHAR(Max),    
    @Email  NVARCHAR(50),   
    @DOB DATETIME,
    @DOJ DATETIME,
    @DOR NVARCHAR(12),
    @Status NVARCHAR(50),
    @Remarks NVARCHAR(Max)

AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    BEGIN TRY
        BEGIN TRANSACTION Employee_Insert
    INSERT 
    INTO
    Employee
    (
        FK_EmployeeTypeID,
        EmployeeName,   
        CellNo, 
        PhNo,   
        Address,    
        Email,  
        DOB,
        DOJ,
        DOR,
        Status,
        Remarks

    )
    VALUES
    (

        @FK_EmployeeTypeID,
        @EmployeeName,  
        @CellNo,    
        @PhNo,  
        @Address,   
        @Email, 
        @DOB,
        @DOJ,
        @DOR,
        @Status,
        @Remarks
    )

        COMMIT TRANSACTION Employee_Insert
    SELECT '1'
    END TRY
    BEGIN CATCH
        SELECT 'Error : ' + ERROR_MESSAGE()
        ROLLBACK TRANSACTION Employee_Insert
    END CATCH

web服务

[WebMethod]
    public string InsUpdDel(string Conn, string ProcName, SqlParameter[] p)
    {
        try
        {
            using (SqlConnection cn = new SqlConnection(Conn))
            {
                if (cn.State == ConnectionState.Open || cn.State == ConnectionState.Broken || cn.State == ConnectionState.Connecting || cn.State == ConnectionState.Executing || cn.State == ConnectionState.Fetching)
                    cn.Close();
                cn.Open();
                SqlCommand cmd = new SqlCommand(ProcName, cn);

                cmd.CommandType = CommandType.StoredProcedure;

                foreach (SqlParameter param in p)
                {
                    cmd.Parameters.Add(param);
                }
                SqlDataReader dr = cmd.ExecuteReader();
                dr.Read();
                if (dr[0].ToString() == "1")
                {
                    return "1";
                }
                else
                {
                    return dr[0].ToString();
                }
                dr.Close();
                cn.Close();
            }
        }
        catch (Exception ex)
        {
            return "Error : " + ex.Message.ToString();
        }

4 个答案:

答案 0 :(得分:1)

首先,您需要检查日期列是否接受空值。
如果没有,那么在那里允许null。

然后你可以使用

command.Parameters.AddWithValue("@param", DBNull.Value);

将所有组合看起来像这样

 param[8] = new Service.SqlParameter();
 param[8].ParameterName = "@DOJ";
 param[8].Value = DOJ==null?DBNull.Value:DOJ;
 param[8].SqlDbType = Service.SqlDbType.DateTime;

你的财产应该是这样的

public DateTime? DOJ
{
    get;
    set;
}

答案 1 :(得分:1)

您需要进行3次更改才能使代码正常工作,

更改1:首先将DateTime变量设为DateTime?

public DateTime? DOB { get; set; }
public DateTime? DOJ { get; set; }

更改2:改为使用DateTime.TryParse

DateTime DOB;
IFormatProvider provider = new System.Globalization.CultureInfo("en-CA", true);
String datetime = txtDOB.Text.Trim();
DateTime.TryParse(datetime, provider, System.Globalization.DateTimeStyles.NoCurrentDateDefault, out DOB);
if (DOB != DateTime.MinValue)
{
    objEmp.DOB = null; 
}
else
{
    objEmp.DOB = date;
}

为DOJ做同样的事。

更改3:此外,当datetime的值为null时,请确保在为sql参数指定DOB值时进行空检查并且如果DOB为null,则指定{{ 1}}

例如:

DBNull.Value

欢迎来到Stackoverflow!

答案 2 :(得分:1)

此代码适用于在sql

中的datetime字段中插入空值
cmd.Parameters.AddWithValue("@from_date", SqlDbType.DateTime).Value = DBNull.Value;

答案 3 :(得分:0)

让你的属性可以为空

public DateTime? DOB
    {
        get;
        set;
    }
    public DateTime? DOJ
    {
        get;
        set;
    }

并使您的代码像这样

IFormatProvider provider = new System.Globalization.CultureInfo("en-CA", true);
        String datetime = txtDOB.Text.Trim();

if(DateTime.TryParse(datetime, provider, System.Globalization.DateTimeStyles.NoCurrentDateDefault, out date))
{
  objEmp.DOB = date;
}