本文介绍了从没有数据的查询中获取列名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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]

我将提供以下输入

Select * from vwGetData

我想在 C#/SQL 中获得以下输出

i want to get below output in C#/SQL

ALIAS1
Field2
Field3
Field4
ALIAS5

ALIAS1, Field2, Field3, Field4, ALIAS5

我想使用 C# 和 SQL 来做到这一点.

I want to do this using C# and SQL.

推荐答案

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

The first thing you would do is make sure that no data gets returned:

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

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

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

您还可以查看 SQL 目录 SYS 视图.

这篇关于从没有数据的查询中获取列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-18 21:01