2008-11-18 257 views
0

我有一個Web服務,它有一個通用函數,可以從存儲過程的結果中返回數據集...某些存儲過程具有可選參數,其值可以爲空,但不是全部。DbNull.Value存儲過程參數?

反正我想在其中具有DBNull.Value

的值的參數來傳遞,我得到這個時出錯生成XML文檔。當這樣做的時候從web服務返回

如果我離開這個參數它工作正常......但真的想知道爲什麼DBNull.Value導致此問題。

回答

1

我認爲這是因爲System.DBNull值是數據庫表中的空值,但過程中的空字段實際上等同於null/nothing關鍵字。不是數據庫空值。我不確定技術上的差異。

但是在你的存儲過程中,你可以將它默認爲null,而不是像你已經完成的那樣發送值,或者我相信如果你發送了null/nothing,它也可以工作。

0

您可以在SqlParemeter中傳遞NULL值,但您必須進行一些類型轉換以確保傳遞正確的空值。

在這個例子中,有一個被稱爲「計數」的參數是一個整數,它被作爲空傳遞:

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