c# – 从SQL Server获取列名

前端之家收集整理的这篇文章主要介绍了c# – 从SQL Server获取列名前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试获取我存储在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服务发送数据的方式.

解决方法

您可以使用下面的查询获取表的列名.下面的查询获取给定名称用户表的所有列:
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();
}
原文链接:https://www.f2er.com/csharp/98759.html

猜你在找的C#相关文章