Get column name from SQL Server

后端 未结 7 2231
礼貌的吻别
礼貌的吻别 2021-02-14 05:32

I\'m trying to get the column names of a table I have stored in SQL Server 2008 R2.

I\'ve literally tried everything but I can\'t seem to find how to do this.

Ri

7条回答
  •  悲&欢浪女
    2021-02-14 06:18

    The original post was close to the goal, Just some small changes and you got it. Here is my solution.

       public List GetColumns(string tableName)
        {
            List colList = new List();
            DataTable dataTable = new DataTable();
    
    
            string cmdString = String.Format("SELECT TOP 0 * FROM {0}", tableName);
    
            if (ConnectionManager != null)
            {
                try
                {
                    using (SqlDataAdapter dataContent = new SqlDataAdapter(cmdString, ConnectionManager.ConnectionToSQL))
                    {
                        dataContent.Fill(dataTable);
    
                        foreach (DataColumn col in dataTable.Columns)
                        {
                           colList.Add(col.ColumnName);
                        }
                    }                   
                }
                catch (Exception ex)
                {
                    InternalError = ex.Message;
                }
            }
    
    
            return colList;
        }
    

提交回复
热议问题