从C#,如何在SQL Server中查找表的列名?

时间:2014-02-07 22:13:02

标签: c# sql-server ado.net

我可以在列表框中找到并显示所有表的所有名称。

但是我需要通过点击按钮显示列表框中所选表格的列名。

我的功能:

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();
            }
        }
    }
}

按钮中的通话功能

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

我的问题:根据选定的表格,我如何找到该表格的列名?用户从列表框中选择表格并点击按钮。

4 个答案:

答案 0 :(得分:3)

只需搜索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;
}

现在,在调用方法中,将返回的列列表添加到用户界面对象中以进行显示

private void button2_Click(object sender, EventArgs e)
{
     string tableName = comboBox1WithTable.SelectedItem.ToString();
     List<string> cols = GetColumnNames(tableName);
     comboBox2WithColumns.DataSource = cols;
}

答案 1 :(得分:2)

SELECT c.name AS ColName
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
WHERE t.name = @SelTableName

只需将下拉列表中的选定表名提供给此SQL脚本。

答案 2 :(得分:1)

要获取所有列名,只需在拥有表名后运行以下SQL命令。

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.
    }
}

答案 3 :(得分:1)

您还需要提供database-name + schema-name + table-name:

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

然后,您可以处理SelectedIndexChanged的{​​{1}}事件。在这里,您可以使用SqlCommand.ExecuteReader(CommandBehavior.SchemaOnly)仅检索架构信息。 DataReader.GetSchemaTable使用列元数据创建ListBox

DataTable