dim mik
dim mik

Reputation: 959

How to get length of a specific column in a table

I am trying to get the length of a specific column in a table which table is from a database called Users in a visual studio C# form application. First of all i know it has to do with the column.length command but since those examples i have a searched i got lost.

Can someone tell me a simple way to get this happen? For more specific information i have a table called user_info and it contains a column which name is searches. I want to get the length of searches into a single variable

Upvotes: 1

Views: 4054

Answers (1)

jtoddcs
jtoddcs

Reputation: 60

Here is the C# code that you need to pull the column size from the database. Make sure you update the connString variable to contain your own SQL server connection string.

Example: "Persist Security Info=False;Integrated Security=true;Initial Catalog=Northwind;server=(local)"

Int32 columnSize = 0;
string sql = "SELECT CHARACTER_MAXIMUM_LENGTH FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'user_info' AND COLUMN_NAME = 'searches'";
string connString = "Your Sql Server Connection String";
using (SqlConnection conn = new SqlConnection(connString))
{
   SqlCommand cmd = new SqlCommand(sql, conn);
   try
   {
      conn.Open();
      columnSize = (Int32)cmd.ExecuteScalar();
   }
   catch (Exception ex)
   {
      Console.WriteLine(ex.Message);
   }
}

Upvotes: 2

Related Questions