SqlDataReader.GetSchemaTable全空字段返回int类型的原因咨询
问题:全为NULL的字段为何被识别为int类型?
C# 获取元数据代码:
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); } }
对应的SQL语句:
select a = 1, b = 'hello', c = null, d = 1.2345 union all select a = 2, b = 'bye', c = null, d = 2.3
执行后字段c全为NULL,但获取到的field.DataType为"int",原因如下:
- SQL中单独的
NULL本身没有绑定固定数据类型,数据库必须为结果集的列推断一个明确类型才能返回。 - 对于这种无额外上下文的
NULL,SQL Server的默认规则是将其推断为int类型——这是数据库内置的类型推断逻辑,int是默认的数值基础类型。 - 你的SQL语句中,两个UNION分支的
c列都是NULL,没有任何指定其他类型的线索(比如用CAST(NULL AS varchar)),所以数据库会统一将该列的类型确定为int。 GetSchemaTable()获取的是数据库返回的结果集结构元数据,这个元数据描述的是列的类型定义,和列中实际存的全是NULL没有关系——类型是列的结构属性,不是由数据值决定的。
内容的提问来源于stack exchange,提问作者Peter
相关产品推荐
相关产品推荐

