I'm trying to retrieve data from SQL Server using C#, but I can't get the SqlDataReader
to return any results. However, the same query works fine in SQL Server Profiler, returning the expected data. I'm not sure why SqlDataReader
isn't working, even though the query itself seems fine.
using System;
using System.Data.SqlClient;
public class Program
{
public static void Main(string[] args)
{
string connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;";
string query = "SELECT top(10) * FROM myTable and many joins...";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(query, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader[0].ToString());
}
reader.Close();
}
}
}
The code runs, but no data is returned. When I run the same query in SQL Server Profiler, I can see the results being returned.
Things I've tried:
ExecuteScalar
and ExecuteNonQuery
instead of ExecuteReader
, but it didn't helpI see the query works fine in SQL Server Profiler and returns the expected data, but in the C# code, no data is returned.
I had faced like this problem, and after removing top(n), the issue was resolved.