使用asp.net中的vb.net将NULL分配到SQL Server datetime列

问题描述 投票:1回答:1

我的应用程序中有3个文本框。第三个是出生日期,用户可以保持空白。

该应用程序将用户输入的值保存到具有3列表的SQL Server数据库中。生日列的数据类型设置为Date,它被定义为可空。

如果用户将生日文本框保持为空,我想将NULL分配给birthday列,所以我尝试了这段代码:

If txtBirthday.Text = "" Then
    command.Parameters.AddWithValue("@Field3", DBNull.value)
End If

但那没用。我也试过(添加Imports System.Data.SqlTypes后):

If txtBirthday.Text = "" Then
   command.Parameters.AddWithValue("@Field3", SqlDateTime.Null)
End If

但那也行不通。

我找到了问题的解决方案,但没有成功。

请帮忙

这是我的完整代码:

Dim Query As String = "INSERT INTO UserInfo (fName, lName, bDay) VALUES (@Field1, @Field2, @Field3);"
Dim connectionString = ConfigurationManager.ConnectionStrings("myapp_con_string").ConnectionString
Using connection As New SqlConnection(connectionString)
    Dim command As New SqlCommand(Query, connection)
    With command
       .Connection = connection
       .CommandType = CommandType.Text
       .CommandText = Query
       .Parameters.AddWithValue("@Field1", txtFirstname.Text)
       .Parameters.AddWithValue("@Field2", txtLastname.Text)
       If txtBirthday.Text = "" Then
           command.Parameters.AddWithValue("@Field3", DBNull.value)
       Else
           command.Parameters.AddWithValue("@Field3", Convert.ToDateTime(txtBirthdat.Text).ToString("yyyy/MM/dd"))
       End If
   End With
   Try
       connection.Open()
       command.ExecuteNonQuery()
       lblMessages.Text = "Data Saved"
   Catch ex As SqlException
       lblMessages.Text = "Data Not Saved"
   End Try
End Using

这是我得到的例外:

{System.Data.SqlClient.SqlError:从字符串转换日期和/或时间时转换失败。}

asp.net sql-server vb.net datetime nullable
1个回答
0
投票

如果您使用的是存储过程,请尝试以下操作。

修改SP参数以设置默认参数值

CREATE PROCEDURE
(
@Name VARCHAR(50),
@Email VARCHAR(255),
@DOB DATE = NULL
)
AS
BEGIN
<Your Code>
END

这意味着。 @Name和@Email是必需的,但如果你没有传递值,@ DOB将为NULL。

现在如果用户没有为出生日期输入值,则不绑定第3个参数,SQL将将其视为NULL

© www.soinside.com 2019 - 2024. All rights reserved.