代码之家  ›  专栏  ›  技术社区  ›  odiseh

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

  •  3
  • odiseh  · 技术社区  · 16 年前

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

    编辑 :

    实际上,我已经写了下面的代码。如您所见,status参数是一种可为空的值类型。 对吗?还是不?

    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 回复  |  直到 16 年前
        1
  •  4
  •   Eddie Groves    16 年前

    你可以试试 DBNull.Value 而不是 null 或者,当nullable完全没有值时,忽略该参数。

        2
  •  0
  •   this. __curious_geek    16 年前

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

      int? nullableParam = null;
      nullableParam = 10; //set the value if any
      //Pass nullableParam to your sp call.
    
        3
  •  0
  •   masoud ramezani    16 年前

    您可以在sp中检查可为空的值,如下所示:

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

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