如何获取数字列的确切类型。规模和精度? [英] How to get the exact type of numeric columns incl. scale and precision?
问题描述
有没有办法知道 DataTable
中列的确切类型?现在我这样做:
Is there a way to know the exact type of a column in a DataTable
? Right now I am doing this:
DataTable st = dataReader.GetSchemaTable();
foreach (DataColumn col in st.Columns)
{
var type = col.DataType;
}
现在使用 type.Name
我可以找到它是否是一个数字( int
或 decimal
..)或 string
但问题是我需要确切的类型,例如,如果在数据库中让列价格
是 NUMBER(4,3)
然后在我的代码中,我只能将类型'Decimal',而没有关于Format 4,3
的信息。
Now with type.Name
I am able to find if it is a number(int
or decimal
..) or string
but the problem is that I need the exact type, for example if in database let say column Rate
is NUMBER(4,3)
then here in my code I am only getting type as 'Decimal' and no information about the Format 4,3
.
现在,我需要根据他们的类型格式化值,例如。如果 Rate = 1.4
,应显示为 0001.400
(根据格式 NUMBER(4 ,3)
)。因此,由于我没有信息,我无法进一步处理这些值。有没有知道相同?
Now the requirement is I need to format the values as per their type for eg. if Rate=1.4
it should be shown as 0001.400
(according to the Format NUMBER(4,3)
). Hence here since I do not have info I am not able to process the values further. Is there anyway to know the same?
谢谢
推荐答案
你可以使用 NumericPrecision
和 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);
}
}
}
更多信息: GetSchemaTable
More informations: GetSchemaTable
我已经用一个新的表单测试了一个单列 NumberColumn
类型 numeric(4,3)
:
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
这篇关于如何获取数字列的确切类型。规模和精度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!