2010-06-01 50 views
3

如何在c#中使用可为空的参数执行存储过程?.net:如何在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; 
     } 
    } 

由于

+1

我们在这里需要更多的细节:哪个数据库服务器? – 2010-06-01 05:58:03

+0

@jeremy:好的,SQL Server – odiseh 2010-06-01 06:02:38

+0

你应该在你的数据适配器上放一个'use()'。 – 2012-08-17 17:06:29

回答

0

如果参数是空的,它必须是一个值类型。该解决方案

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

如果@code是:假设你有一个int为空的参数,那么你可以通过这种方式..

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

使用可为空对象的GetValueOrDefault方法或其默认值。 – VoodooChild 2010-06-01 06:08:18

+0

+1好点:) – odiseh 2010-06-01 06:21:28

+0

int = 0的默认值不是我们建议的(null) – odiseh 2010-06-01 09:25:44

0

您可以在SP检查空值象下面这样null,那么这个条件将不适用。

+0

我已经在我的SP中完成了这项工作。 – odiseh 2010-06-01 07:29:13

+0

更简单的方法是: 'where code = ISNULL(@code,code)' 如果您的参数为null,它将使用列本身的值作为比较。 – 2012-08-17 17:04:50

4

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

+0

你的意思是我应该把Deriveparameter放在if块中? – odiseh 2010-06-01 07:30:15

+0

我没有做很多的工作与SqlCommand和数据集,但我会建议尝试如果测试如:if(status.HasValue){command.Parameters [“@ Status”]。Value = status} – eddiegroves 2010-06-01 07:35:20

+0

你的建议使用DBNull.value)会生成一个错误,指示int之间没有隐式转换?和DBNull, – odiseh 2010-06-01 07:47:10

相关问题