1

I am developing an application in C# in Visual Studio 2008. I connected a SQL Server 2008 database with it.

I want to count the number of columns so that I can loop around them to get the particular data.

I can figure it out columns by going to the database but I am joing 4-5 tables in my programs so I want to know if I can count the columns.

Can anyone help me in this?

Thank you Shyam

5
  • How are you connecting to the DB? Linq2Sql, ADO.NET, EF? Commented Feb 7, 2013 at 14:22
  • 2
    What have you tried so far? You can get a list of tables, columns, etc. by examining the database catalog (e.g. sys.tables and sys.columns), but it sounds like you already know that. It's unclear what the question is here. Commented Feb 7, 2013 at 14:23
  • "I want to count the number of columns so that i can loop around them to get the particular data" I think you're doing things wrong. You can select all columns you need in one step: SELECT T1Col1=T1.col1,T2Col1=T2.col1,col2,col3 From T1 INNER JOIN T2 ON T1.Col1=T2.Col1. There is no need to loop. Commented Feb 7, 2013 at 14:24
  • This is similiar question with answer [CountOfColumns][1] [1]: stackoverflow.com/questions/10699166/… Commented Feb 7, 2013 at 14:25
  • Thank You Guys you guys are really helpful. I learned lot of different things. Commented Feb 7, 2013 at 15:01

6 Answers 6

4
select count(*) from INFORMATION_SCHEMA.columns where TABLE_NAME = 'YourTableName'
Sign up to request clarification or add additional context in comments.

1 Comment

But how can you store that number in one variable in C#?
1

Something like this ?

SELECT COUNT(*)
FROM sys.columns c 
INNER JOIN sys.tables t ON c.object_id = t.object_id
WHERE t.name = 'yourTable'

See this page provided wy TaronPro to know how to retrieve the result.

5 Comments

Or even without the join: FROM sys.columns WHERE [object_id] = OBJECT_ID('dbo.yourTable');
Thanks for fast responces. @Yuck the question is how can i get that number of all the columns. I am using SELECT COUNT(*) From sys.columns but it just select it not give me that number. how can i get the number? I am new with SQL SERVER and C# too.
See what @TaronPro suggested : stackoverflow.com/questions/10699166/…
using (SqlConnection con = new SqlConnection(connectionString)) { con.Open(); using (SqlCommand command = new SqlCommand("SELECT * FROM Status", con)) using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { Console.WriteLine(reader[0].ToString()+"\t"+reader[1].ToString()+"\t"+reader[2].ToString()+"\t"+reader[3].ToString()); } } } This is my code
This is not I wanted but still i learned something.Thanks for your help
1

If you are using SQLConnection object to connect to DB, use its GetSchema method to get list of all columns without querying.

    using (SqlConnection connection = new SqlConnection(connectionString))
   {
       // Connect to the database then retrieve the schema information.
       connection.Open();
       DataTable table = connection.GetSchema("Tables");
        ..
        ..
        ..

If you want to know columns for specific owner, table or table type, use restriction within GetSchema method.

    string[] restrictions = new string[4];
    restrictions[1] = "dbo";
    DataTable table = connection.GetSchema("Tables", restrictions);

for more information refer this link.

Comments

0

What I did in a similar situation is that when I executed the query I retrieved all the data into a DataSet.

When I got the DataSet I opened the first table (ds.Tables[0]). Obviously you check first for existance.

When you have the table then its as simple as performing a

dt.Columns.Count;

In summary DS.Tables[0].Columns.Count To find a specific column by name you loop through and find the one that

for (z=0; z < dt.Columns.Count; z++)
{
  // check to see if the column name is the required name passed in.
  if (dt.Columns[z].ColumnName == fieldName)
  {
    // If the column was found then retrieve it 
    //dc = dt.Columns[z];
    // and stop looking the rest of the columns
    requiredColumn = z;
    break;
 }

}

Then to find the data you need I would then loop through the rows of the table and get the field for that column... ie...

string return = dr.Field<string>(requiredColumn);

Probalby not the best way of doing it but it works. Obviously if the data contained in the field is not string then you need to pass the appropriate type...

dr.Field<decimal>(requiredColumn)
dr.Field<int>(requiredColumn) 

etc

Rgds George

1 Comment

Thank you so much for your fast responses.
0

The reader itself gives you the number of columns. This is useful when you don't want to know the number rows of a specific table or view but from an ad-hoc query.

You can dump the columns like this

string sql = "SELECT * FROM my query";
SqlCommand cmd = new SqlCommand(sql, connection);
using (SqlDataReader reader = cmd.ExecuteReader()) {
    while (reader.Read()) {
        for (int i = 0; i < reader.FieldCount; i++) {
            Console.WriteLine("{0} = {1}",
                              reader.GetName(i),
                              reader.IsDBNull(i) ? "NULL" : reader.GetValue(i));
        }
        Console.WriteLine("---------------");
    }
}

Comments

0

you can use Microsoft.SqlServer.Management.Smo namespace to get the number of columns in a specified table as follows 1 . add Microsoft.SqlServer.Management.Smo dll in your project and use the namespace Microsoft.SqlServer.Management.Smo 2 . write the follwing code

private int colCount()
{
      Server server=new Server(".\\SQLEXPRESS");
      Database database=Server.Databases["your database name"];
      Table table=database.Tables["your table name"];
      return (table.Columns.Count);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.