2012-11-06 25 views
2

我有下面這段代碼:執行標量捕獲錯誤的沒有記錄的情況下返回

Dim lJobName As String = "" 
SQLCommand.CommandText = "Select JobName from Jobs where Id = @Id " 
SQLCommand.Parameters.Add(New SqlParameter("@Id", SqlDbType.Int)) 
SQLCommand.Parameters(0).Value = var_id 
lJobName = SQLCommand.ExecuteScalar() 

問題如何捕捉到,如果不找到任何記錄?

回答

0

我會盡量避免比較字符串到沒什麼,即使它在VB的工作。

Visual Basic .NET運行時將Nothing評估爲空字符串;那是, 」」。但是,.NET Framework不會,只要嘗試在Nothing上執行字符串操作就會拋出異常。作爲當前顯示無論手冊上說

加pseudocoder的答案不會工作(oJobname是從來沒有設置任何東西)

Dim lJobName as String = String.Empty 
Dim oJobName as object = SqlCommand.ExecuteScalar() 

If oJobName Is Nothing Then 
    'Do something with the error condition 
Else 
    lJobName = oJobName.ToString 
End If 
+0

String.Empty與Nothing不是一回事,這就是爲什麼我沒有't use'If String.IsNullOrEmpty(lJobName)Then' – pseudocoder

+0

哇,主要剪切和粘貼錯誤,我改變了我的帖子,以顯示我的意圖。 – PatFromCanada

+0

我明白你要去那裏了。儘管如此,String仍然沒有任何值。不使用它的唯一原因是如果你想實現一個適用於非空值類型的模式,比如'Integer'或'Decimal',這可以用你的答案來說明。儘管如此,你應該糾正你關於「不評估爲空字符串」的不準確陳述。 – pseudocoder

0

的ExecuteScalar()返回Nothing如果有一個空的結果集,這應該分配到一個字符串時被保留,所以我想試試這個:

Dim lJobName as String = String.Empty 
lJobName = SqlCommand.ExecuteScalar() 
If lJobName Is Nothing Then 
    'Do something with the error condition 
Else 
    'Do something with lJobName which contains a valid result. 
End If 

當然,如果你並不能幫助你導致SqlException,但它應該處理在結果集中找不到行的問題。

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx

+1

不是真的DBNull.Value。 ExecuteScalar return'結果集中第一行的第一列或空引用(在Visual Basic中爲Nothing)' – Steve

+0

感謝您糾正我無法閱讀文檔。我更新了我的答案。 – pseudocoder

+0

是更好的使用Is Nothing比IsDbNull也lJobName = oJobName是一個隱式轉換,不會與嚴格的選項一起工作,更好地調用oJobName上的.ToString – PatFromCanada

3

,比較沒有什麼不起作用。所以當結果集爲空時,不會觸發If lJobName Is Nothing

相較於DBNull.Value爲我所做的工作:

If lJobName Is DBNull.Value Then 
    'Do something with the error condition 
Else 
    'Do something with lJobName which contains a valid result. 
End If 

值得注意的是,當結果集爲空(即沒有記錄被發現),這不是一個「錯誤」。

0

我認爲這是可能以處理查詢的語句這種情況:

SELECT ISNULL(FieldID,「0」)FROM表名

,並隨後在程序驗證結果:

如果再 ...... 其他 ...... ENDIF

相關問題