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

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

我有一个 View 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 执行此操作。

最佳答案

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

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 .

关于c# - 从没有数据的查询中获取列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7159524/

相关文章:

sql - 整数 pgsql 的输入语法无效

c# - NHibernate 没有连接到 sql server

c# - 在我的应用程序中获取打开的连接字符串数

sql - 在 SQL Server 中检查临时表中是否存在列总是返回 false

c# - 带有节标题和数据绑定(bind)的列表框

C# WPF框架中的Page和MainWindow之间的数据交换

sql - SELECT 查询中的索引扫描速度较慢

c# - 在 LINQ 中选择计数

c# - 如何使用 .NET Action 执行参数数量未知的方法?

sql - SQL Server 2008 中的 FREETEXT 查询不是短语匹配