Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Column names from a query without data

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.

like image 960
Thakur Avatar asked Aug 23 '11 10:08

Thakur


People also ask

How do I get only column names in SQL?

In SQL Server, you can select COLUMN_NAME from INFORMATION_SCHEMA. COLUMNS .

How do I retrieve column names?

You can also use the following query to get the table's column names: SELECT * FROM sys. columns WHERE object_id = OBJECT_ID('News')

How do I get all column names in SQL Server?

The System Stored Procedure sp_columns returns Column names with additional information from the Database table in SQL Server.


1 Answers

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.

like image 74
Jonathan Dickinson Avatar answered Oct 06 '22 19:10

Jonathan Dickinson