简体   繁体   中英

From C#, how to find the names of the columns of a table in SQL Server?

I can find and display all names of all tables in a listbox.

But I need display column names of selected table from listbox by click a button.

My function :

public void GetTableNames()
{
    string strConnect = "Data Source=;Initial Catalog=DATA;User ID=sa;Password=***";
    using (SqlConnection con = new SqlConnection(strConnect))
    {
        con.Open();

        using (SqlCommand com = new SqlCommand(@"SELECT * FROM INFORMATION_SCHEMA.TABLES
                                                 WHERE TABLE_TYPE='BASE TABLE'  
                                                 ORDER BY TABLE_NAME ASC ", con))
        {
            using (SqlDataReader reader = com.ExecuteReader())
            {
                listBox2.Items.Clear();
                int counter = 0;
                while (reader.Read())
                {
                    counter++;
                    listBox2.Items.Add((string)reader["TABLE_NAME"]);
                }

                lblTablesCount.Text = counter.ToString();
            }
        }
    }
}

Call function in button

private void button1_Click(object sender, EventArgs e)     
{
    GetTableNames();
}

My question : Given a selected table, how can I find the names of the columns of that table? The user picks the table from a listbox and clicks a button.

Just search in INFORMATION_SCHEMA.COLUMNS

SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @yourtablename




public List<string> GetColumnNames(string tableName)
{
    List<string> columns = new List<string>();
    string strConnect = ".........";
    using (SqlConnection con = new SqlConnection(strConnect))
    {
         con.Open();
         using (SqlCommand com = new SqlCommand(@"SELECT COLUMN_NAME 
                                 FROM INFORMATION_SCHEMA.COLUMNS 
                                 WHERE TABLE_NAME = @yourtablename", con))
         {

             com.Parameters.AddWithValue("@yourtableName", tableName);
             using (SqlDataReader reader = com.ExecuteReader())
             {
                 columns.Add(reader["COLUMN_NAME"].ToString());
             }
         }
    }
    return columns;
}

now, in the calling method add the returned columns list to your user interface object for display

private void button2_Click(object sender, EventArgs e)
{
     string tableName = comboBox1WithTable.SelectedItem.ToString();
     List<string> cols = GetColumnNames(tableName);
     comboBox2WithColumns.DataSource = cols;
}
SELECT c.name AS ColName
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
WHERE t.name = @SelTableName

Just provide the selected table name from the dropdownlist to this SQL script.

To get all column names you just need to run the following SQL Command after you have the table name.

private void GetColumnNames(string tableName)
{
    string query = "SELECT * FROM myDatabase.INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @TableName";
    using (var conn = new SqlConnection(myConnectionString))
    using (var cmd = new SqlCommand(query, conn))
    {
        cmd.Parameters.AddWithValue("@TableName", tableName)
        conn.Open();
        var reader = cmd.ExecuteReader();
        //Store the contents of reader in a variable to update your list box.
    }
}

You need to provide also the database-name + schema-name + table-name:

string table = string.Format("{0}.{1}.{2}", reader[0], reader[1], reader[2]); 
listBox2.Items.Add(table);

Then you can handle the SelectedIndexChanged event of the ListBox . Here you can use SqlCommand.ExecuteReader(CommandBehavior.SchemaOnly) to retrieve the schema informations only. DataReader.GetSchemaTable creates a DataTable with the column-metadata:

private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
    string table = listBox2.SelectedItem.ToString();
    using (SqlConnection con = new SqlConnection(strConnect))
    {
        con.Open();
        using (SqlCommand com = new SqlCommand(@"SELECT * FROM " + table, con))
        {
            using (SqlDataReader reader = com.ExecuteReader(CommandBehavior.SchemaOnly))
            {
                listBoxColumns.Items.Clear();
                DataTable schemaTable = reader.GetSchemaTable();
                foreach(DataRow colRow in schemaTable.Rows)
                    listBoxColumns.Items.Add(colRow.Field<String>("ColumnName"));
            }
        }
    }
}

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