Vb.net - 处理从 SQL 命令对象返回的空值或无值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13798202/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 11:31:12  来源:igfitidea点击:

Vb.net - Handling null or no values returned from SQL Command object

vb.net

提问by Conrad Jagger

we got this sql query:

我们得到了这个 sql 查询:

Select EmployeeDesignation from Employee where EmployeeName = Paramater1 

(Parameter1 is value is passed to this)

(Parameter1 是传递给这个的值)

We are using this statement: lEmployeeDesignation = _SQLCommand.ExecuteScalar()

我们正在使用这个语句: lEmployeeDesignation = _SQLCommand.ExecuteScalar()

3 scenario's:

3个场景:

  1. Returns the employee Designation (record exists in table)
  2. No value is set in database for Parameter1 - so should return NULL (record exists but has no value)
  3. No employee record exists so returns nothing (record doesn't exists)
  1. 返回员工名称(表中存在记录)
  2. 在数据库中没有为 Parameter1 设置值 - 所以应该返回 NULL(记录存在但没有值)
  3. 不存在员工记录,因此不返回任何内容(记录不存在)

I'm struggling with 2 and 3 scenario - incase of Scenario 3 we want the application to fail, but struggling how to trap this error. regards

我在 2 和 3 场景中挣扎 - 在场景 3 的情况下,我们希望应用程序失败,但正在努力如何捕获此错误。问候

采纳答案by Steve

lEmployeeDesignation = _SQLCommand.ExecuteScalar()
if lEmployeeDesignation IsNot Nothing AndAlso lEmployeeDesignation <> DBNull.Value then
    ' you have found your data....' 
Else
    if lEmployeeDesignation = DBNull.Value then
       ' you have a record for parameter1 but EmployeeDesignation field is null'
    End If
End If

Notice the use of AndAlso to shortcircuit the evaluation process. If the first condition is false then the second one is not evaluated

请注意使用 AndAlso 来缩短求值过程。如果第一个条件为假,则不评估第二个条件

回答by Ciarán

You could eliminate the Null entirely by...

你可以完全消除 Null ......

Select IsNull(Max(EmployeeDesignation),0) from Employee where EmployeeName = Paramater1

It's not a terribly good thing to do, but it works and as long as you're not doing too many of them it'll be fine.

这不是一件非常好的事情,但它是有效的,只要你不做太多事情就可以了。

You could also put in a Count(EmployeeDesignation)=0 to check scenario 3 though of course this couldn't be done on the same query or you would have to use a reader

您也可以输入 Count(EmployeeDesignation)=0 来检查场景 3,尽管这当然不能在同一个查询中完成,否则您将不得不使用阅读器