I am Trying to generate random Ids from a given table. I can see the random number generated in debug but when I reach to reader.Read() line it shows Enumeration yielded no results.
I couldn't quite get what I am missing.
private static void GetRandomId(int maxValue)
{
string connectionString =
"Data Source=local;Initial Catalog=Test;user id=Test;password=Test123;";
string queryString = @"SELECT TOP 1 Id from Pointer WHERE Id > (RAND() * @max);";
using (var connection = new SqlConnection(connectionString))
{
var command = new SqlCommand(queryString, connection);
command.Parameters.AddWithValue("@max", maxValue);
connection.Open();
using (var reader = command.ExecuteReader()) <-- // Here I can see the randon value generated
{
while (reader.Read())
{
//Here reader shows : Enumeration yielded no results
Console.WriteLine("Value", reader[1]);
reader.Close();
}
}
}
}
Idbe larger than the product ofmaxValueandRAND()?reader[int]is zero-based. So your data (if you get any) will be inreader[0]. Btw if you get to theConsole.WriteLineline, that means that there is at least 1 row of results. And finally, callingreader.Close()is not necessary (and would in fact break it if there was more than 1 line returned). Theusingtakes care of that. Maybe you wanted to usebreak;?