.net:如何在c#中使用可为空的参数执行存储过程?

时间:2010-06-01 05:57:08

标签: .net sql-server stored-procedures parameters nullable

如何在c#中使用可为空的参数执行存储过程?

修改

实际上,我写了下面的代码。如您所见,status参数是可以为null的值类型。 这是对的吗?不是吗?

public void LoadAll(DataTable tb, int? status=null)
    {
        try
        {
            using (SqlConnection connection = new SqlConnection())
            {
                connection.ConnectionString = this.connectionString;

                using (SqlCommand command = connection.CreateCommand())
                {
                    command.CommandType = CommandType.StoredProcedure;
                    command.CommandText = "USP_OrganizationChartSelect";
                    SqlCommandBuilder.DeriveParameters(command);
                    command.Parameters["@Status"].Value = status.HasValue ? status : null;
                    if (connection.State != ConnectionState.Open)
                        connection.Open();
                    SqlDataAdapter adapter = new SqlDataAdapter(command);
                    tb.Clear();
                    adapter.Fill(tb);
                    adapter.Dispose();
                    adapter = null;
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

由于

3 个答案:

答案 0 :(得分:4)

您可以尝试使用DBNull.Value而不是null,或者在可以为空的情况下完全没有值时省略参数。

答案 1 :(得分:0)

如果参数可以为空,则它必须是值类型。假设你有一个int nullable参数,那么你可以这样传递它。

  int? nullableParam = null;
  nullableParam = 10; //set the value if any
  //Pass nullableParam to your sp call.

答案 2 :(得分:0)

你可以检查sp中的可空值,如下所示:

select * from table
where (code = @code or @code is null)

通过此解决方案,如果@code为null,则此条件将不适用。