如何从SQL Server 2014数据库中获取所选表中的字段?

时间:2014-05-14 09:09:16

标签: c# sql-server

这是我的代码:

namespace Modulul_3_proiect
{
    public partial class FormSimpleWizard : Form
    {
        public FormSimpleWizard()
        {
            InitializeComponent();
            incarcaComboBoxSimpleWiz(comboBoxWS);
        }

        //method to extract tables from BD
        public IList<string> ListTables()
         {
            DBConnection db = DBConnection.getConexiune;
            SqlConnection conexiune = db.conn;

            List<string> tables = new List<string>();
            DataTable dt = conexiune.GetSchema("Tables");
            foreach (DataRow row in dt.Rows)
            {
                string tablename = (string)row[2];
                tables.Add(tablename);
            }
            return tables;
        }
        //method to load combobox with tables
        private void incarcaComboBoxSimpleWiz(ComboBox cb)
        {
            IList<string> tabeleWizard=ListTables();
            cb.Items.Clear();
            cb.Items.Add("Select tables");
            foreach (String tip in tabeleWizard)
                cb.Items.Add(tip);
            cb.SelectedIndex = 0;
        }
    }
}

在我使用SQL Server数据库中的表加载组合框之后,我想在组合框中获取所选表的字段并在文本框多行中显示它们,以便我可以在之后进行查询。

1 个答案:

答案 0 :(得分:0)

public string[] getColumnsName(string tname)
{
    List<string> listacolumnas=new List<string>();
    using (SqlConnection connection = new SqlConnection(Connection))
        using (SqlCommand command = connection.CreateCommand())
        {
            command.CommandText = "select c.name from sys.columns c inner join sys.tables t on t.object_id = c.object_id and t.name = tname and t.type = 'U'";
            connection.Open();
            using (var reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    listacolumnas.Add(reader.GetString(0));
                }
            }
        }
    return listacolumnas.ToArray();
}

你确定要传递正确的表名吗?

试试这个

从sys.columns中选择c.name c。在t.object_id = c.object_id和t.name ='你的表名'和t.type ='U'

的内连接sys.tables t

在t-sql上