从没有数据的查询中获取列名

时间:2011-08-23 10:21:01

标签: c# sql sql-server sql-server-2008 tsql

我有一个视图vwGetData,它从两个表t1,t2获取数据并有字段:

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

我将提供以下输入

Select * from vwGetData

我希望在C#/ SQL

中获得低于输出
ALIAS1
Field2
Field3
Field4
ALIAS5

ALIAS1, Field2, Field3, Field4, ALIAS5

我想用C#和SQL来做这件事。

7 个答案:

答案 0 :(得分:28)

您要做的第一件事就是确保没有返回任何数据:

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

现在假设您知道如何设置DataReader,您将执行以下操作:

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"]);
  }
}

您还可以查看SQL Catalog SYS Views

答案 1 :(得分:11)

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

答案 2 :(得分:6)

我找到的最简单的方法就是这个。

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));
    }
}

这将打印您拥有的每行结果的列名。

答案 3 :(得分:2)

有一个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();

答案 4 :(得分:1)

您还可以将数据加载到DataTable中,如下所示:

DataTable dtTable = new DataTable();

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

并检索第一行中的列,如下所示:

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

或者遍历所有行并引用列,如下所示:

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

答案 5 :(得分:0)

我使用以下方法获取所有列名称。

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;
    }

控制台应用程序版本

GetSchemaTable返回的DataTable中的行包含有关表列的信息,我想要onlu列名。

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

答案 6 :(得分:0)

你可以获得所有列列表

1.在SQL查询编辑器中只写表名

2.选择表格名称,然后按Alt + F1