12

我正在尝试获取存储在 SQL Server 2008 R2 中的表的列名。

我已经尝试了一切,但我似乎无法找到如何做到这一点。

现在这是我在 C# 中的代码

public string[] getColumnsName()
{
        List<string> listacolumnas=new List<string>();

        using (SqlConnection connection = new SqlConnection(Connection))
        using (SqlCommand command = connection.CreateCommand())
        {
            command.CommandText = "SELECT TOP 0 * FROM Usuarios";
            connection.Open();

            using (var reader = command.ExecuteReader(CommandBehavior.KeyInfo))
            {
                reader.Read();

                var table = reader.GetSchemaTable();

                foreach (DataColumn column in table.Columns)
                {
                    listacolumnas.Add(column.ColumnName);
                }
            }
        }
        return listacolumnas.ToArray();
    }

但这正在返回我以下

<string>ColumnName</string>
<string>ColumnOrdinal</string>
<string>ColumnSize</string>
<string>NumericPrecision</string>
<string>NumericScale</string>
<string>IsUnique</string>
<string>IsKey</string>
<string>BaseServerName</string>
<string>BaseCatalogName</string>
<string>BaseColumnName</string>
<string>BaseSchemaName</string>
<string>BaseTableName</string>
<string>DataType</string>
<string>AllowDBNull</string>
<string>ProviderType</string>
<string>IsAliased</string>
<string>IsExpression</string>
<string>IsIdentity</string>
<string>IsAutoIncrement</string>
<string>IsRowVersion</string>
<string>IsHidden</string>
<string>IsLong</string>
<string>IsReadOnly</string>
<string>ProviderSpecificDataType</string>
<string>DataTypeName</string>
<string>XmlSchemaCollectionDatabase</string>
<string>XmlSchemaCollectionOwningSchema</string>
<string>XmlSchemaCollectionName</string>
<string>UdtAssemblyQualifiedName</string>
<string>NonVersionedProviderType</string>
<string>IsColumnSet</string>

有任何想法吗?

它显示<string>标签,因为这是我的 Web 服务发送数据的方式。

4

7 回答 7

28

您可以使用下面的查询来获取表的列名。下面的查询获取给定名称的用户表的所有列:

select c.name from sys.columns c
inner join sys.tables t 
on t.object_id = c.object_id
and t.name = 'Usuarios' and t.type = 'U'

在您的代码中,它将如下所示:

public string[] getColumnsName()
{
    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 = 'Usuarios' and t.type = 'U'";
            connection.Open();
            using (var reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    listacolumnas.Add(reader.GetString(0));
                }
            }
        }
    return listacolumnas.ToArray();
}
于 2013-10-15T22:45:49.947 回答
21

我通常使用 GetSchema 方法来检索特定于列的信息,这个片段将返回字符串列表中的列名:

        using (SqlConnection conn = new SqlConnection("<ConnectionString>"))
        {
            string[] restrictions = new string[4] { null, null, "<TableName>", null };
            conn.Open();
            var columnList = conn.GetSchema("Columns", restrictions).AsEnumerable().Select(s => s.Field<String>("Column_Name")).ToList();
        }
于 2013-10-15T23:36:36.643 回答
9
SELECT COLUMN_NAME
FROM   
INFORMATION_SCHEMA.COLUMNS 
WHERE   
TABLE_NAME = 'YourTable' 
于 2013-10-15T22:44:31.350 回答
3
public string[] getColumnsName()
    {
        List<string> listacolumnas=new List<string>();
        using (SqlConnection connection = new SqlConnection(Connection))
        using (SqlCommand command = connection.CreateCommand())
        {
            command.CommandText = "select column_name from information_schema.columns where table_name = 'Usuarios'";
            connection.Open(;
            using (var reader = command.ExecuteReader(CommandBehavior.KeyInfo))
            {
                reader.Read();

                var table = reader.GetSchemaTable();
                foreach (DataColumn column in table.Columns)
                {
                    listacolumnas.Add(column.ColumnName);

                }
            }
        }
        return listacolumnas.ToArray();
    }
于 2013-10-15T22:45:03.487 回答
2

原始帖子接近目标,只需进行一些小的更改,您就明白了。这是我的解决方案。

   public List<string> GetColumns(string tableName)
    {
        List<string> colList = new List<string>();
        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;
    }
于 2018-08-20T17:21:29.017 回答
0

目前,我可以想到两种方法:

  • 在纯 SQL Server SQL 中,您可以使用INFORMATION_SCHEMA.COLUMNS. 在那里,您需要为表选择行,与 column 匹配TABLE_NAME
  • 由于您使用的是 C#,因此SqlDataReaderExecuteReader. 该类提供了一个属性FieldCount,用于列数,以及一个方法GetName(int),将列号作为其参数并返回列的名称。
于 2013-10-15T22:50:50.657 回答
0
sp_columns - http://technet.microsoft.com/en-us/library/ms176077.aspx

这种类型的东西有很多内置的存储过程。

于 2013-10-15T22:47:30.683 回答