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.
Yep - with Microsoft.Data.SqlClient in a Visual Studio 2022 C# console application, you can execute a SELECT query that returns three rows and use SqlDataReader to read each row individually. You do not need to know the number of rows in advance; reader.Read() advances to the next row and returns false when there are no more rows.
Try the following:
using Microsoft.Data.SqlClient;
using System;
class Program
{
static void Main()
{
string connectionString =
"Server=YOUR_SERVER;Database=YOUR_DATABASE;" +
"Integrated Security=True;TrustServerCertificate=True;";
string sql = @"
SELECT Code
FROM (VALUES
('ABC'),
('DEF'),
('GHI')
) AS Codes(Code);";
using SqlConnection connection =
new SqlConnection(connectionString);
using SqlCommand command =
new SqlCommand(sql, connection);
connection.Open();
using SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string code = reader.GetString(0);
Console.WriteLine(code);
}
}
}
The output should be:
ABC
DEF
GHI
In this example, the VALUES clause creates three sample rows, each containing one code. Replace that query with your actual SELECT statement and update the connection string to match your environment. reader.GetString(0) retrieves the first column, using a zero-based column index. If your column can contain NULL, check reader.IsDBNull(0) before calling GetString(0).
If the above response helps answer your question, remember to "Accept Answer" so that others in the community facing similar issues can easily find the solution. Your contribution is highly appreciated.
hth
Marcin