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.
Use SqlCommand.ExecuteReader() and call Read() in a loop; each successful call advances the SqlDataReader to the next returned row.^1^
using Microsoft.Data.SqlClient;
string connectionString =
"Server=YOUR_SERVER;Database=YOUR_DATABASE;Integrated Security=True;TrustServerCertificate=True;";
const string sql = """
SELECT TOP (3) Code
FROM dbo.YourTable
ORDER BY Code;
""";
using var connection = new SqlConnection(connectionString);
using var command = new SqlCommand(sql, connection);
connection.Open();
using var reader = command.ExecuteReader();
while (reader.Read())
{
string code = reader.GetString(0);
Console.WriteLine(code);
}
Replace:
-
YOUR_SERVERandYOUR_DATABASEwith your SQL Server details. -
dbo.YourTablewith the table name. -
Codewith the actual column name. - The connection string with your authentication settings if you are not using Windows authentication.
GetString(0) means “read the first selected column as a string.” If Code is an integer, use reader.GetInt32(0) instead. Typed accessors reduce unnecessary type conversion.^1^
The reader starts before the first row, so Read() must be called before accessing column values. It returns false when there are no more rows.^2^
The using declarations dispose the reader, command, and connection even if an exception occurs. Do not execute another command on the same connection while this reader remains open; the connection is occupied by that reader until it is closed.^1^
For posting C# in Q&A, place three backticks followed by csharp before the code and three backticks after it, as shown above.
References