簡體   English   中英

獲取表的SQL Server架構

[英]getting the SQL Server Schema for a table

我有以下C#代碼,我試圖返回存儲過程結果以及這些結果的模式。 以下是我的代碼(簡化)目前的樣子......

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。

更好的答案如下: 2013 Microsoft支持本文介紹了多種檢索表信息的方法,這里有一種方法。

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

如果你正在使用System.Data.Common.DbCommand,那么,我想你可以打電話

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

[編輯]

你也可以使用

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

要么

db.ExecuteDataSet

這是一個有用的鏈接

希望它能回答你的問題

獲取SQL Server存儲過程的架構的最佳方法是使用sql:

EXEC sp_help MyStoredProcedure

請參閱http://msdn.microsoft.com/en-us/library/aa933429(SQL.80).aspx

令人尷尬的舊代碼時間。 這是我第一次學習.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;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM