简体   繁体   中英

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

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

  • Size
  • Precision
  • Scale

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

Table1:

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

Reference2

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? , 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

So just use this:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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