14

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.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Thakur
  • 1,890
  • 5
  • 23
  • 33

8 Answers8

29

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.

mark.monteiro
  • 2,609
  • 2
  • 33
  • 38
Jonathan Dickinson
  • 9,050
  • 1
  • 37
  • 60
  • this is what i needed TOP 0 does it :) – Thakur Aug 23 '11 at 10:37
  • you could also use SELECT TOP 0 [vwGetData].* FROM [vwGetData] WHERE 1 = 2; – Mark Kram Jul 05 '12 at 16:25
  • 3
    What about using [`SET FMTONLY`](http://msdn.microsoft.com/en-us/library/ms173839.aspx) to turn off return of rows? This functionality is built into SQL for situations like this. Example: `SET FMTONLY ON SELECT * FROM vwGetData SET FMTONLY OFF` – Ben Gribaudo Jul 15 '14 at 20:36
  • 4
    instead `WHERE 1 = 2`, you can use `command.ExecuteReader(CommandBehavior.SchemaOnly))` – dovid Jun 24 '17 at 22:55
11
SELECT COLUMN_NAME
FROM   
INFORMATION_SCHEMA.COLUMNS 
WHERE   
TABLE_NAME = 'vwGetData' 
ORDER BY 
ORDINAL_POSITION ASC; 
Silx
  • 2,663
  • 20
  • 21
  • I am beginner in C#. How do i use this query in the c# code block? –  Oct 10 '12 at 06:56
  • Maybe it's my SQL Server version (2008) but none of the other proposed solutions actually work, not even the accepted answer. Only this one did, just FYI – Hamman Samuel Feb 20 '14 at 20:38
6

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.

Matthieu M.
  • 61
  • 1
  • 3
  • Worked like a charm for me in a situation where pretty much all other solutions failed - so thanks a lot! – Rami Apr 02 '15 at 16:40
2

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();
Preet Sangha
  • 64,563
  • 18
  • 145
  • 216
1

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"];
}
Gaui
  • 8,723
  • 16
  • 64
  • 91
0

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

Sumanth
  • 224
  • 2
  • 3
0

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;
A.Bahrami
  • 134
  • 7
0

you can get all column list

1.In sql query editor write only table name

2.select table name and press Alt+F1

NIts577
  • 420
  • 3
  • 13