0

I'm suddenly experiencing issues with obtaining data from the MS SQL DB using the SQLDataReader. The problem is that it's only happening for one specific table and the exactly the same approach works for all other tables.

This table contains ~24.000 rows of data and I'm obtaining only column ID which is a nvarchar(max) in DB and I'm mapping it to string.

When I use the SQL command, I get DBNull. The most interesting thing is that if I add TOP command to the query, it suddenly works and return all rows.

This doesn't work and return null:

SELECT [ID] FROM [Table] This works and return all data: SELECT TOP(25000) [ID] FROM [Table] This is my code:

string sql = $@"SELECT {columnList} FROM [{TableName}] {whereString} {orderByString}";

using (SqlCommand command = new SqlCommand(sql, conn))
{
    using (SqlDataReader reader = command.ExecuteReader())
    {
        while (reader.Read())
        {
            var i = 0;
            if (typeof(T) == typeof(string))
            {
                var value = reader.GetValue(i);
                ret.Add((T)value);
            }
        }
    }
}

conn.Close();
}

return ret;

Does anyone know why is this happening and why usage of TOP suddenly fixes it?

How can I fix this without using the TOP because it makes no sense to use it to get all rows.

9
  • If you load the data in a datatable using the SqlDataAdapter how many rows count do you see ? Commented Nov 2, 2022 at 9:58
  • @Steve I have tested it with SqlDataAdapter and "dataSet.Tables[0].Rows.Count" contains correct number of rows even when I don't use TOP. Commented Nov 2, 2022 at 10:04
  • What is ret in this case, and where do you see DBNull? reader.GetValue can produce a DBNull if the source column is NULL (that is, there are IDs in your table that are NULL). Commented Nov 2, 2022 at 10:07
  • Use SQL Server Management Studio and try query in SSMS. Either there is no data or the credentials aren't working. You can check the log files in SSMS in explorer under management tab to see if there were any errors when you ran the c# code. Commented Nov 2, 2022 at 10:27
  • 1
    Just for sanity's sake, could you try SELECT * FROM [Table] WHERE [ID] IS NULL in SSMS anyway? Also, could you print the actual contents of sql to verify the query is what you think it is? Barring a very odd bug in the client or a non-deterministic view (i.e. Table isn't really a table), retrieving a DBNull where there is no NULL should be impossible. Commented Nov 2, 2022 at 10:33

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.