简体   繁体   English

DbNull.Value存储过程参数?

[英]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. 我有一个Web服务,该服务具有一个泛型函数,该函数从存储过程的结果返回数据集...一些存储过程具有可选参数,其中值可以为null,但并非始终如此。

Anyhow I am trying to pass in a parameter which has a value of DBNull.Value 无论如何,我试图传递一个具有DBNull.Value值的参数

and I get this There was an error generating the XML document. 我明白了生成XML文档时出错。 back from the web service when doing so 从Web服务返回时

If I leave this parameter out it works fine... but really would like to know why DBNull.Value causes this problem. 如果我不设置此参数,它将很好地工作...但是真的很想知道为什么DBNull.Value会导致此问题。

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. 我相信这是因为System.DBNull值在数据库表中为null,但是过程中的null字段实际上等于null / nothing关键字。 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. 但是在您存储的proc中,您可以将其默认设置为null,而不像已经完成的那样发送该值,否则我相信如果您发送null /则它也将起作用。

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. 您可以在SqlParemeter中传递NULL值,但是必须进行一些类型转换以确保传递正确的null值。

In this example, there is a parameter called "Count" which is an integer, which gets passed as null: 在此示例中,有一个名为“ Count”的参数,它是一个整数,将作为空值传递:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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