SQL C#

Reading with NextResult()

This C# program demonstrates how to read data with an SQLReader using multiple results and the NextResult() function in a database for Microsoft SQL in C#.

Program.cs

using System;
using System.Data.SqlClient;

namespace ReadingWithNextResult {
    class Program {
        static void Main(string[] args) {
            Console.Write(ReadMultipleResults("apostles"));
        }

        public static string ReadMultipleResults(string sTable) {
            // The using block ensures that the connection is closed when it exits this block.
            using (SqlConnection qConnection = new SqlConnection(
                    @"Server=localhost\SQLEXPRESS01;Database=catholic;Trusted_Connection=True;")) {
                qConnection.Open();
                string sTableEntries = "";
                // The selection command
                using (SqlCommand qCommand =
                        new SqlCommand("SELECT name FROM apostles;" +
                            "SELECT name FROM sacraments", qConnection)) {
                    using (SqlDataReader qReader = qCommand.ExecuteReader()) {
                        do {
                            sTableEntries += "Result:\n";
                            sTableEntries += "----------------------------\n";
                            // Read the next line, while available
                            while (qReader.Read()) {
                                // The count is the number of elements per line, one in this case.
                                object[] qaValues = new object[qReader.FieldCount];
                                qReader.GetValues(qaValues);
                                // Run through the elements in each line, only one in this case.
                                foreach (object qData in qaValues) {
                                    sTableEntries += String.Format("{0,-20}", qData);
                                }
                                sTableEntries += "\n";
                            }
                            sTableEntries += "\n";
                            // Get the result from the next query.
                        } while (qReader.NextResult());
                    }
                }
                return sTableEntries;
            }
        }
    }
}
 

Output

Result:
----------------------------
John
Andrew
Peter

Result:
----------------------------
Baptism
Eucharist
Confirmation
Penance
Anointing of the Sick
Holy Matrimony
Holy Orders

Press any key to continue . . .
 

Tables

Tables
 

Apostles Table

Apostles Table
 

Sacraments Table

Sacraments Table
 
 

© 2007–2026 XoaX.net LLC. All rights reserved.