Get column name from SQL Server

后端 未结 7 2226
礼貌的吻别
礼貌的吻别 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-14 06:07

    You can use the query below to get the column names for your table. The query below gets all the columns for a user table of a given name:

    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'
    

    In your code, it will look like that:

    public string[] getColumnsName()
    {
        List listacolumnas=new List();
        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();
    }
    

提交回复
热议问题