我可以在列表框中查找并显示所有表的所有名称。
但我需要通过单击按钮显示列表框中所选表格的列名。
我的功能:
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();
}
我的问题:给定一个选定的表,我如何找到该表的列的名称?用户从列表框中选择该表并单击一个按钮。
最佳答案
只需在 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;
}
关于c# - 在 C# 中,如何在 SQL Server 中查找表的列名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21638750/