简体   繁体   English

从SQL Server提取列详细信息时,指定的转换无效

[英]Specified cast is not valid while fetching column details from SQL Server

I am trying to fetch following details of columns from SQL Server: 我试图从SQL Server中获取列的以下详细信息:

  • Size 尺寸
  • Precision 精确
  • Scale 规模

I am successfully getting data when I have below schema for table: 当我具有以下表的架构时,我成功获取数据:

Table1: 表格1:

Col1 : varchar(40),null)
Col2 : varchar(2,null)
Col3 : varchar(57,null)
Col4 : varchar(245 ,null)
Col5 : datetime(not null)

But I'm getting an error 但是我出错了

Specified cast is not valid. 指定的演员表无效。

in case of this schema: 在这种情况下:

Col1 : varchar(34,null)
Col2 : varchar(1066,null)
Col3 : varchar(500,null)
Col4 : varchar(600,null)
Col5 : numeric(31,13,null)
Col6 : numeric(31,13,null)
Col7 : datetime(null)

Code: 码:

String[] columnRestrictions = new String[4];
columnRestrictions[0] = 'MyDb';
columnRestrictions[1] = 'dbo';
columnRestrictions[2] = 'Employee';

using (SqlConnection con = new SqlConnection("MyConnectionString"))
{
    con.Open();
    var columns = con.GetSchema("Columns", columnRestrictions).AsEnumerable()
         .Select
          (
                 t => new 
                 {
                     Name = t[3].ToString(),
                     Datatype = t.Field<string>("DATA_TYPE"),
                     IsNullable = t.Field<string>("is_nullable"),
                     Size = t.Field<int?>("character_maximum_length"),
                     NumericPrecision = t.Field<int?>("NUMERIC_PRECISION"), //error on this field
                     NumericScale = t.Field<int?>("NUMERIC_SCALE")
                 }).ToList();

Source : 资源 :

Reference1 参考1

Reference2 参考2

Update : this line is causing the issue 更新 :此行引起问题

NumericPrecision = t.Field<int?>("NUMERIC_PRECISION"), //error on this field

How can I resolve this error and fetch size, precision and scale for columns? 如何解决此错误并获取列的大小,精度和小数位数?

The problem in your code is that you are casting a byte to int? 您的代码中的问题是您要将一个byteint? , the Field -method supports nullable types (if the column can be null), but it doesn't convert from byte? Field方法支持可为null的类型(如果列可以为null),但是它不从byte?转换byte? to int? int? . It throws this exception instead. 而是抛出此异常。 Source 资源

So just use this: 所以只要使用这个:

NumericPrecision = t.Field<byte?>("NUMERIC_PRECISION"),

You can always look at the DataColumn 's DataType property. 您始终可以查看DataColumnDataType属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM