从SQL Server提取列详细信息时,指定的转换无效 [英] Specified cast is not valid while fetching column details from SQL Server

查看:282
本文介绍了从SQL Server提取列详细信息时,指定的转换无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从SQL Server中获取列的以下详细信息:

I am trying to fetch following details of columns from SQL Server:

  • 大小
  • 精度
  • 规模

当我具有以下表的架构时,我成功获取数据:

I am successfully getting data when I have below schema for table:

表1:

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

但是我遇到了错误

指定的演员表无效.

Specified cast is not valid.

在这种情况下:

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)

代码:

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();

来源:

参考2

更新:此行引起了问题

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

如何解决此错误并获取列的大小,精度和小数位数?

How can I resolve this error and fetch size, precision and scale for columns?

推荐答案

代码中的问题是将byte强制转换为int?Field方法支持可为null的类型(如果列可以为null),但不会从byte?转换为int?.而是抛出此异常. 来源

The problem in your code is that you are casting a byte to int?, the Field-method supports nullable types (if the column can be null), but it doesn't convert from byte? to int?. It throws this exception instead. Source

所以只用这个:

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

您始终可以查看DataColumnDataType属性.

You can always look at the DataColumn's DataType property.

这篇关于从SQL Server提取列详细信息时,指定的转换无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆