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.
retin this case, and where do you seeDBNull?reader.GetValuecan produce aDBNullif the source column isNULL(that is, there are IDs in your table that areNULL).SELECT * FROM [Table] WHERE [ID] IS NULLin SSMS anyway? Also, could you print the actual contents ofsqlto verify the query is what you think it is? Barring a very odd bug in the client or a non-deterministic view (i.e.Tableisn't really a table), retrieving aDBNullwhere there is noNULLshould be impossible.