SqlDataReader.GetSchemaTable returns data type = int when all values are null

205 Views Asked by At

The following code snippet:

using (DataTable schemaTable = reader.GetSchemaTable())
{
    for (int i = 0; i < reader.FieldCount; i++)
    {

        DataRow drow = schemaTable.Rows[i];

        string name = drow.Field<string>("ColumnName");
        string dataType = drow.Field<string>("DataTypeName");
        bool isNullable = drow.Field<bool>("AllowDBNull");
        int maxLength = drow.Field<int>("ColumnSize");
        int precision = drow.Field<short>("NumericPrecision");
        int scale = drow.Field<short>("NumericScale");

        DatabaseField field = new DatabaseField(name, dataType, isNullable, maxLength, precision, scale);
        fields.Add(field);

    }
}

where the SQL string variable is:

select a = 1, b = 'hello', c = null,  d = 1.2345
union all
select a = 2, b = 'bye', c = null,  d = 2.3

effectively returns field.DataType = "int" for the field named c. No value was provided in that field. My question is why "int" and not simply a null value? Why would "int' be favored over something else?

1

There are 1 best solutions below

5
Charlieface On

This is nothing to do with SqlDataReader.

The default data type of NULL returned by SQL Server is int, if there is no other deduced type.

You can prove this with the following

SELECT name, system_type_name
FROM sys.dm_exec_describe_first_result_set(N'SELECT NULL AS SomeNull;', DEFAULT, DEFAULT);

db<>fiddle