Is it possible for my code to find out the size of varchar column?

  • Thread starter Thread starter john
  • Start date Start date
J

john

I want to ask the DB how large a varchar column is so I can ensure
that strings being inserted there are not too long.

thanks in advance,
John
 
Here is one way:

// cn = valid OleDbConnection to your database
DataTable colschemaTable;
int col_length;
colschemaTable = cn.GetOleDbSchemaTable
(OleDbSchemaGuid.Columns,
new object[] {null, null, "MyTable", null});
foreach (DataRow row in colschemaTable.Rows)
{
if (row["COLUMN_NAME"] = "yourcolumn")
col_length = row["CHARACTER_MAXIMUM_LENGTH"];
}
see on-line doc for OLE DB CColumns for explanation of
the other items you may want to access.
 
Thanks, I also found that I can do a query like this:

SELECT character_maximum_length
FROM INFORMATION_SCHEMA.columns
WHERE table_name = 'whatever'
 
Back
Top