Exception problem

Peter_1985 2,686 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?

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
13,977 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,006 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,652 questions
{count} votes

Accepted answer
  1. Erland Sommarskog 112.7K Reputation points MVP
    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.