How to get the exact type of numeric columns incl. scale and precision?

这一生的挚爱 提交于 2019-12-03 14:04:19

You can use NumericPrecision and NumericScale:

using (var con = new SqlConnection(Properties.Settings.Default.RM2ConnectionString))
using (var cmd = new SqlCommand("SELECT * FROM dbo.Test", con))
{
    con.Open();
    using (var reader = cmd.ExecuteReader())
    using (var schemaTable = reader.GetSchemaTable())
    {
        foreach (DataRow row in schemaTable.Rows)
        {
            string column = row.Field<string>("ColumnName");
            string type = row.Field<string>("DataTypeName");
            short precision = row.Field<short>("NumericPrecision");
            short scale = row.Field<short>("NumericScale");
            Console.WriteLine("Column: {0} Type: {1} Precision: {2} Scale: {3}", column, type, precision, scale);
        }
    }
}

More informations: GetSchemaTable

I have tested it with a fresh table with a single column NumberColumn of type numeric(4, 3):

Column: NumberColumn Type: decimal Precision: 4 Scale: 3

The DataTable returned by dataReader.GetSchemaTable() is the schema of the underlying result. This table contains, those many records as many columns in the underlying table. So you need to loop through the rows. Each row contains the metadata of the single column of the underlying table. You can get the metadata of the column as below

DataTable st = reader.GetSchemaTable();
                    foreach (DataRow row in st.Rows)
                    {
                        Console.Write(string.Format("ColumnName:{0} DataType:{1} Ordinal:{2} Precision:{3} Size:{4} Scale:{5}", 
                            row["ColumnName"], row["DataTypeName"], row["ColumnOrdinal"], 
                            row["NumericPrecision"], row["ColumnSize"], row["NumericScale"]));
                    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!