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.
In SQL Server, you can select COLUMN_NAME from INFORMATION_SCHEMA. COLUMNS .
You can also use the following query to get the table's column names: SELECT * FROM sys. columns WHERE object_id = OBJECT_ID('News')
The System Stored Procedure sp_columns returns Column names with additional information from the Database table in SQL Server.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With