简体   繁体   中英

DbNull.Value Stored Procedure Parameter?

I have a web service which has a generic function that returns a dataset from results of stored procedures... Some of the stored procedures have optional parameters where the value can be null but not all the time.

Anyhow I am trying to pass in a parameter which has a value of DBNull.Value

and I get this There was an error generating the XML document. back from the web service when doing so

If I leave this parameter out it works fine... but really would like to know why DBNull.Value causes this problem.

I beleive that's becuase a System.DBNull value is a null in database table but a null field in a procedure effectively equates to the null/nothing keyword. Not a database null value. I'm not sure of the technical differences under the hood.

But in your stored proc you can just default it to null and not send the value as you've already done or i believe if you sent null/nothing it would also work.

You can pass a NULL value in the SqlParemeter, but you must do some type conversion to make sure the right null value gets passed.

In this example, there is a parameter called "Count" which is an integer, which gets passed as null:

Using dtResult as New DataTable 
  Using cn as SqlConnection = New SqlConnection ("ConnectionString") 
    Using sqlcmd as SqlCommand - New SqlCommand("StoredProceName", cn) with {.CommandType=CommandType.StoredProcedure}

      Dim sp As SqlParameter
      sp = sqlcmd.Parameters.Add("@Count", SqlDbType.Int)
      sp.value = CType(Nothing, SqlTypes.SqlInt32) 

      Using myDR as SqlDataReader = sqlcmd.ExecuteReader
        dtResult.Load(myDR)
      end using 
      return dtResult 
    End Using ' For sqlcmd 
    cn.Close() ' Close the connection 
  end using ' For cn 
end using ' For dtResult

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