2010-06-01 55 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

相關問題