Exception problem

Peter_1985 2,736 Reputation points
2024-05-10T08:22:21.91+00:00

Hi,

I've got issue

User's image

due to this line below.

reader = cmd.ExecuteReader();

Can it be owing to no record returned?

Developer technologies Transact-SQL
SQL Server Other
Developer technologies C#
{count} votes

Accepted answer
  1. Erland Sommarskog 121.4K Reputation points MVP Volunteer Moderator
    2024-05-10T21:41:52.05+00:00

    Can it be owing to no record returned?

    The other way round. No rows are being returned, because your query/batch run into an error.

    You need to capture the error message with an exception handler and get the text of the error message.

    Here is a simple sample program of how to capture exceptions with SqlDataReader_

    using System.Data.SqlClient;
    
    public static class SqlErrorRepro {
       private static string sqlBatchText = @"
          BEGIN TRY
             SELECT name, log(max_length) FROM sys.columns
          END TRY
          BEGIN CATCH
              ; THROW
          END CATCH";
    
       private static string connString =
            @"Data Source=.;Integrated Security=SSPI;Database=tempdb";
    
       public static void Main() {
          try {
             using (SqlConnection cn = new SqlConnection(connString))
             using (SqlCommand cmd = new SqlCommand(sqlBatchText, cn)) {
                int rowCount = 0;
                cn.Open();
                using (SqlDataReader reader = cmd.ExecuteReader()) {
                   while(reader.Read()) { ++rowCount; };
                   while(reader.NextResult());
                }
                System.Console.WriteLine("{0} rows read", rowCount);
             }
          }
          catch (System.Exception ex){
             System.Console.WriteLine("ERROR: " + ex.Message);
          }
       }
    }
    
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.