2
votes

I have a database table. Is there a query that gets the names of the columns in a table?

Example:

Name || Age || Gender
Tom  || 30  || male
Kate || 20  || Female

I want a query to get the column names: Name , Age, Gender

Thanks you

edit: Sorry about some missing info:

I am using an OleDB connection in C# to read data from an excel sheet

3
It depends on a dbms you are using. MSSQLSERVER, Oracle, MySql? Please specify it in tags.George Polevoy
I have an excel sheet and I am reading data from it using an OleDB connection. Hope this is what you meanY2theZ
There's a sample here of getting column names from Excel via an OleDbConnectionMartin Smith

3 Answers

1
votes

You can retrieve a list of columns in a table like:

select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'YourTable'

INFORMATION_SCHEMA is an ISO standard, so it works on most databases.

0
votes

I believe you're after the SHOW COLUMNS query.

SHOW COLUMNS FROM mytable

More info: http://dev.mysql.com/doc/refman/5.0/en/show-columns.html

0
votes

i wanted to upload the columns of a table from Excel, so I uploaded the table in a Dataset and then checked the column names and inserted in database. you can get an idea from the below code

for (int i = 0; i < dsUpload.Tables[0].Columns.Count; i++)
                    {
                        if (dsUpload.Tables[0].Columns[i].ColumnName.ToString() != "")
                        {
                            // Assigning ColumnName
                            objExcelUpload.ColumnName = dsUpload.Tables[0].Columns[i].ColumnName.ToString().Replace("'", "''").Replace("<", "&lt;").Replace(">", "&gt;").Trim();
                            if (!objExcelUpload.ifColumnNameExist("insert"))
                            {
                                if (objExcelUpload.ColumnName != "")
                                {
                                    objExcelUpload.insertColumns();    
                                }

                            }
                            else
                            {
                                ErrorLabel.Text = "The column name already exists. Please select a different name.";
                                return;
                            }

                        }
                    }

Here ds Upload is a dataset name and the code useful for you is

objExcelUpload.ColumnName = dsUpload.Tables[0].Columns[i].ColumnName.ToString()

which is checked in a loop of all the available columns

for (int i = 0; i < dsUpload.Tables[0].Columns.Count; i++)

Let me know if you need any clarification :-)