2009-04-08 96 views
1

我有下面的C#代码,我试图返回存储过程结果以及这些结果的架构。以下是我的代码(简化版)目前的样子...获取表的SQL Server架构

Database db = DatabaseFactory.CreateDatabase(); 
DbCommand dbCommand = db.GetStoredProcCommand("MyStoredProcedure"); 
IDataReader drData = db.ExecuteReader(dbCommand); 

DataTable tblSchema; 
tblSchema = drData.GetSchemaTable(); 

GetSchemaTable返回空白。我已经读过,我需要将CommandBehavior.KeyInfo传递给ExecuteReader方法,但我不清楚这是如何将代码结构化的方式,因为我将dbCommand传递给ExecuteReader。

回答

1

如果使用System.Data.Common.DbCommand的话,我想你可以打电话

IDataReader drData = dbCommand.ExecuteReader(CommandBehavior.KeyInfo); 

[编辑]

您还可以使用

DataSet ds = new DataSet(); 
db.LoadDataSet(dbCommand, ds, "tableName"); 

db.ExecuteDataSet 

这是一个link找到的有用

希望这回答了你的问题

1

尴尬的旧代码时间。这是我第一次学习.NET 1.1时使用的,教我的人坚持使用DataSets/Tables而不是业务对象。它大约有5年的历史,从旧的图书馆中剥离出来,但给了一个表名,它会给你一个包含表格模式的数据集。

public static DataSet GetTableSchema(string tableName) 
{ 
    string query = string.Format("SELECT TOP 0 * FROM {0}", tableName); 

    using (SqlConnection localSqlConn = new SqlConnection(GetConnectionString())) 
    { 
     DataSet ds = new DataSet(); 

     SqlCommand sqlCmd = new SqlCommand(query, localSqlConn); 
     SqlDataAdapter sda = new SqlDataAdapter(sqlCmd); 

     sda.FillSchema(ds, SchemaType.Source, tableName); 
     sda.Fill(ds, tableName); 

     sda.Dispose(); 

     return ds; 
    } 
} 
1

更好的答案将是如下: 2013 Microsoft Support 文章展示多种方式来检索表信息,这里是一个方法。

SqlConnection cn = new SqlConnection(); 
SqlCommand cmd = new SqlCommand(); 
DataTable schemaTable; 
SqlDataReader myReader; 

//Open a connection to the SQL Server Northwind database. 
cn.ConnectionString = "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();