简体   繁体   中英

Assign null value to a decimal field in SQL

I want to assign null value in a field in SQL 2014 which has a data type, decimal . I tried to use theses codes but I didn't get the way I wanted (providing that other fieldnames and values are present.)

query = "INSERT INTO DBNAME.TLTRPRGP(DECIMALVAL) VALUES(@DECIMALVAL)"
params = New String() {"BLGSCD"}
values = New String() {Nothing}

SaveUpdateDelete(query, params, values)


query = "INSERT INTO DBNAME.TLTRPRGP(DECIMALVAL) VALUES(@DECIMALVAL)"
params = New String() {"BLGSCD"}
values = New String() {DbNull.Value}

SaveUpdateDelete(query, params, values)


query = "INSERT INTO DBNAME.TLTRPRGP(DECIMALVAL) VALUES(@DECIMALVAL)"
params = New String() {"BLGSCD"}
values = New String() {VbNull}

SaveUpdateDelete(query, params, values)


Private Sub SaveUpdateDelete(ByVal sql As String, ByVal parameters() As String, ByVal Values() As String)
    If con.State = ConnectionState.Open Then
        con.Close()
    End If
    con.Open()

    Dim command As New SqlCommand
    command = New SqlCommand(sql, con)

    For i = 0 To parameters.Count - 1
        command.Parameters.AddWithValue("@" & parameters(i).ToString, Values(i))
    Next
    command.CommandText = sql
    command.ExecuteNonQuery()

    con.Close()
End Sub

The first code returns 0 . The second returns syntax error saying "Value System.DbNull.Value cannot be converted to String" . The third code returns 1 . All these codes failed to return the right value which is suppose to be NULL or EMPTY . What else is there to try?

the issue is with the datatype of the values: you constrain it to be a string but there are values that cannot be converted to strings (eg: DBNull.Value ).

the solution is to use the generic object as the datatype for the parameters passed to the function SaveUpdateDelete .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM