【问题标题】:Get Column names from a query without data从没有数据的查询中获取列名
【发布时间】:2011-11-01 20:06:20
【问题描述】:

我有一个视图 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 来完成这项工作。

【问题讨论】:

  • 两张表是如何相互关联的?
  • 也许只是添加“where 1 = 0”并检查返回的列?
  • 贴出你目前写的代码?问题似乎是什么?

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


【解决方案1】:

你要做的第一件事是确保没有数据被返回:

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

【讨论】:

  • 这是我需要的 TOP 0 做到了 :)
  • 你也可以使用 SELECT TOP 0 [vwGetData].* FROM [vwGetData] WHERE 1 = 2;
  • 使用SET FMTONLY 关闭行返回怎么样?针对此类情况,此功能内置于 SQL 中。示例:SET FMTONLY ON SELECT * FROM vwGetData SET FMTONLY OFF
  • 代替WHERE 1 = 2,你可以使用command.ExecuteReader(CommandBehavior.SchemaOnly))
【解决方案2】:
SELECT COLUMN_NAME
FROM   
INFORMATION_SCHEMA.COLUMNS 
WHERE   
TABLE_NAME = 'vwGetData' 
ORDER BY 
ORDINAL_POSITION ASC; 

【讨论】:

  • 我是 C# 的初学者。如何在 c# 代码块中使用此查询?
  • 也许这是我的 SQL Server 版本 (2008),但其他提议的解决方案都没有实际工作,甚至没有接受的答案。只有这个,仅供参考
【解决方案3】:

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

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

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

【讨论】:

  • 在几乎所有其他解决方案都失败的情况下,这对我来说就像一个魅力 - 非常感谢!
【解决方案4】:

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

【讨论】:

  • 他们真的可以在示例代码中处理资源!
  • 这是否获取所有数据(SELECT * FROM Employees)然后返回列信息?
【解决方案5】:

您还可以将数据加载到 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"];
}

【讨论】:

    【解决方案6】:

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

    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

    【讨论】:

    • 您能详细说明一下吗?这是怎么回事
    【解决方案7】:

    查询 在mysql中

    SELECT * FROM vwGetData LIMIT 0
    

    在sqlserver中

    SELECT TOP 0 * FROM vwGetData
    

    在甲骨文中

    SELECT * FROM vwGetData WHERE ROWNUM <=0
    

    然后从 c# 执行查询 例如“甲骨文”

    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】:

      你可以得到所有的列列表

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

      2.选择表名并按Alt+F1

      【讨论】:

        猜你喜欢
        • 2013-09-21
        • 2013-08-20
        • 2014-05-22
        • 1970-01-01
        • 2023-03-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多