Tha*_*kur 14 c# sql t-sql sql-server sql-server-2008
我有一个视图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来做这件事.
Jon*_*son 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.
Sil*_*ilx 11
SELECT COLUMN_NAME
FROM   
INFORMATION_SCHEMA.COLUMNS 
WHERE   
TABLE_NAME = 'vwGetData' 
ORDER BY 
ORDINAL_POSITION ASC; 
我找到的最简单的方法就是这样.
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));
    }
}
这将打印您拥有的每行结果的列名称.
| 归档时间: | 
 | 
| 查看次数: | 56207 次 | 
| 最近记录: |