可空类型在VB.NET中是否可用?如果可用,是否可以使用可空整数与接受NULL值的SQL Server字段一起使用?请提供示例。
可空类型在VB.NET中是否可用?如果可用,是否可以使用可空整数与接受NULL值的SQL Server字段一起使用?请提供示例。
VB.Net确实有可空类型,可以通过以下两种不同的方式进行声明。
Dim iNullable As Integer?
或者Dim iNullable As Nullable(Of Integer)
在VB中,你不能将Null
、Nothing
或DBNull
赋给裸的 Integer
, 但是你可以使用Nullable(Of Integer)
代替:
Dim x As Integer? = Nothing
有时(但很少)将整数值装箱到一个 Object
中(可以是 Nothing
)是有意义的。
Dim a As Integer = Nothing
但是在此之后,以下条件成立:
a = 0
- JochenNothing
就像 C# 中的 default(T)
。当与值类型或引用类型一起使用时,它的行为是不同的。 - nikeeeSystem.Int32
)不能直接为空;然而,有一个名为 Nullable-of-T
的类型可使任何值类型变得类似于可空。请注意,您可能需要检查数据库中的 DBNull
而不是 null
/Nothing
。
因此,您可以做出非常相似的事情。
Nothing
会被转换为默认值。如果要像使用null
一样使用Nothing
,则需要将其强制转换为正确的可空类型。Dim str As String
Dim int As Nullable(Of Integer) ' or use As Integer?
Dim reader As SqlDataReader
Dim colA As Integer = reader.GetOrdinal("colA")
Dim colB As Integer = reader.GetOrdinal("colB")
str = If(reader.IsDBNull(colA), DirectCast(Nothing, String), reader.GetString(colA))
int = If(reader.IsDBNull(colB), DirectCast(Nothing, Nullable(Of Integer)), reader.GetInt32(colB))
如下所述,我知道从客户端代码将NULL输入数据库的唯一方法是在SQL中使用等于NULL的默认值。
因此,在更新/插入存储过程中,您可以使用以下内容:
create proc dbo.UpdateSomeTable
@Id int,
@Status bit = NULL
as
begin
update dbo.SomeTable
set Status = @Status
where Id = @Id
end
在代码中的某个地方
Dim pars As List(Of SqlParameter) = New List(Of SqlParameter)
With pars
.Add(New SqlParameter("@Id", LogbookNoteId))
If Flag Then
.Add(New SqlParameter("@Status", Flag))
End If
End With
ExecuteNonQuery("dbo.UpdateSomeTable", pars, CommandType.StoredProcedure)
不行。您必须修改插入或更新查询,以便不添加(或更新)该值以在数据库中获取空值。