Get Column names from a query without data

2019-03-24 14:54发布

问题:

I have a view vwGetData which gets data from two tables t1,t2 and has fields:

t1.Field1 [ALIAS1], t1.Field2, t2.Field3, t2.Field4, t2.Field5 [ALIAS5]

I will provide below input

Select * from vwGetData

i want to get below output in C#/SQL

ALIAS1
Field2
Field3
Field4
ALIAS5

or

ALIAS1, Field2, Field3, Field4, ALIAS5

I want to do this using C# and SQL.

回答1:

The first thing you would do is make sure that no data gets returned:

SELECT TOP 0 [vwGetData].* FROM [vwGetData] WHERE 1 = 2;

Now assuming you know how to set up a DataReader you would do the following:

using(var reader = command.ExecuteReader())
{
  // This will return false - we don't care, we just want to make sure the schema table is there.
  reader.Read();

  var tableSchema = reader.GetSchemaTable();

  // Each row in the table schema describes a column
  foreach (DataRow row in tableSchema.Rows)
  {
    Console.WriteLine(row["ColumnName"]);
  }
}

You can also could also look into the SQL Catalog SYS Views.



回答2:

SELECT COLUMN_NAME
FROM   
INFORMATION_SCHEMA.COLUMNS 
WHERE   
TABLE_NAME = 'vwGetData' 
ORDER BY 
ORDINAL_POSITION ASC; 


回答3:

The easiest way I found is this.

using (SqlCommand command = new SqlCommand("SELECT * FROM vwGetData", conn))
{
    SqlDataReader reader = command.ExecuteReader();
    while (reader.Read())
    {
        for (int i = 0; i < reader.FieldCount; i++)
            Console.Writeline(reader.GetName(i));
    }
}

This will print the column names for each line of result you have.



回答4:

There is a good sample here:

using System.Data;
using System.Data.OleDb;

OleDbConnection cn = new OleDbConnection();
OleDbCommand cmd = new OleDbCommand();
DataTable schemaTable; 
OleDbDataReader myReader; 

//Open a connection to the SQL Server Northwind database.
cn.ConnectionString = "Provider=SQLOLEDB;Data Source=server;User ID=login;
                       Password=password;Initial Catalog=Northwind";
cn.Open();

//Retrieve records from the Employees table into a DataReader.
cmd.Connection = cn;
cmd.CommandText = "SELECT * FROM Employees";
myReader = cmd.ExecuteReader(CommandBehavior.KeyInfo); 

//Retrieve column schema into a DataTable.
schemaTable = myReader.GetSchemaTable();

//For each field in the table...
foreach (DataRow myField in schemaTable.Rows){
    //For each property of the field...
    foreach (DataColumn myProperty in schemaTable.Columns) {
    //Display the field name and value.
    Console.WriteLine(myProperty.ColumnName + " = " + myField[myProperty].ToString());
    }
    Console.WriteLine();

    //Pause.
    Console.ReadLine();
}

//Always close the DataReader and connection.
myReader.Close();
cn.Close();


回答5:

You can also load the data into a DataTable, like so:

DataTable dtTable = new DataTable();

using (SqlCommand command = new SqlCommand("SELECT * FROM Table", conn))
{
    SqlDataReader reader = command.ExecuteReader();
    dtTable.Load(reader);
}

And retrieve the column in the first row, like so:

var column = dtTable.Rows[0]["YourColumn"];

Or loop through all the rows and reference the column, like so:

foreach (var c in dtTable.AsEnumerable())
{
    var column = c["YourColumn"];
}


回答6:

I am getting all the column names using the following method.

private static List<string> GetColumnNamesFromTableSchema(IDataReader reader)
    {
        var schemaTable = reader.GetSchemaTable();
        var columnNames = new List<string>();
        if (schemaTable != null)
            columnNames.AddRange(from DataRow row in schemaTable.Rows select row["ColumnName"].ToString());
        return columnNames;
    }

Console Application Version

Rows in DataTable returned by GetSchemaTable contains information about the table columns and I want onlu column name.

using (SqlConnection connection = new SqlConnection("Connection String"))
                {
                    SqlCommand command = new SqlCommand("select top 10 * from myschema.MyTable", connection);
                    connection.Open();
                    SqlDataReader reader = command.ExecuteReaderAsync().Result;  
                    DataTable schemaTable = reader.GetSchemaTable();
                    foreach (DataRow row in schemaTable.Rows)
                    {
                        //Console.WriteLine(row["ColumnName"]);
                        foreach (DataColumn column in schemaTable.Columns)
                        {    
                            Console.WriteLine(string.Format("{0} = {1}", column.ColumnName, row[column.ColumnName]));                                   

                        }
                        Console.WriteLine(">>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<");
                    }
}

https://support.microsoft.com/en-us/kb/310107



回答7:

query in mysql

SELECT * FROM vwGetData LIMIT 0

in sqlserver

SELECT TOP 0 * FROM vwGetData

in oracle

SELECT * FROM vwGetData WHERE ROWNUM <=0

then execute query from c# for example 'oracle'

OracleDataAdapter adapter = new OracleDataAdapter(query, connection);
System.Data.DataTable result = new System.Data.DataTable();
adapter.Fill(result);

List<string> columns = new List<string>();
foreach(DataColumn item in result.Columns)
{
    columns.Add(item.ColumnName);
}
return columns;


回答8:

you can get all column list

1.In sql query editor write only table name

2.select table name and press Alt+F1