Execute Scalar to trap error in case of no records returned

后端 未结 4 1551
轻奢々
轻奢々 2021-01-20 06:33

I have got this code below:

Dim lJobName As String = \"\"
SQLCommand.CommandText = \"Select JobName from Jobs where Id = @Id \"
SQLCommand.Parameters.Add(New         


        
4条回答
  •  耶瑟儿~
    2021-01-20 07:26

    ExecuteScalar() returns Nothing if there is an empty result set, which should be preserved when assigning into a string, so I would try this:

    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
    

    Of course this doesn't help you if you cause a SqlException, but it should handle the problem of no rows found in the result set.

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

提交回复
热议问题