Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

vb.net - Preserving NULL values in a Double Variable

I'm working on a vb.net application which imports from an Excel spreadsheet.

If rdr.HasRows Then
        Do While rdr.Read()
            If rdr.GetValue(0).Equals(System.DBNull.Value) Then
                Return Nothing
            Else
                Return rdr.GetValue(0)
            End If
        Loop
    Else

I was using string value to store the double values and when preparing the database statement I'd use this code:

If (LastDayAverage = Nothing) Then
            command.Parameters.AddWithValue("@WF_LAST_DAY_TAG", System.DBNull.Value)
        Else
            command.Parameters.AddWithValue("@WF_LAST_DAY_TAG", Convert.ToDecimal(LastDayAverage))
        End If

I now have some data with quite a few decimal places and the data was put into the string variable in scientific notation, so this seems to be the wrong approach. It didn't seem right using the string variable to begin with.

If I use a double or decimal type variable, the blank excel values come across as 0.0.

How can I preserve the blank values?


Note: I have tried

Variable as Nullabe(Of Double)

But when passing the value to the SQL insert I get: "Nullable object must have a value."


Solution:

Fixed by changing the datatype of the parameter in the sub I was calling and then using Variable.HasValue to do the conditional DBNull insert.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I don't know which API you're using to do database inserts, but with many of them, including ADO.NET, the proper way to insert nulls is to use DBNull.Value. So my recommendation is that you use Nullable(Of Double) in your VB code, but then when it comes time to do the insert, you'd substitute any null values with DBNull.Value.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...