代码之家  ›  专栏  ›  技术社区  ›  PHeiberg

获取存储过程结果的.NET架构

  •  9
  • PHeiberg  · 技术社区  · 14 年前

    我在T-SQL中有几个存储过程,其中每个存储过程都有一个固定的结果集模式。

    我需要将每个过程的结果集映射到POCO对象,并需要结果集中每个列的列名和类型。是否有快速访问信息的方法?

    到目前为止,我发现的最佳方法是从.NET访问每个存储过程,并在IDataReader/IDataRecord上编写自己的扩展方法,以便将信息(列名和类型)转储出去。

    例如,执行以下查询的存储过程:

    SELECT Id, IntField, NullableIntField, VarcharField, DateField FROM SomeTable
    

    需要我提供地图信息:

    Id - Guid
    IntField - System.Int32
    NullableIntField - Nullable<System.Int32>
    VarcharField - String
    DateField - DateTime
    
    4 回复  |  直到 14 年前
        1
  •  10
  •   Amitabh    9 年前

    我想你应该能用 sqldatareader.getSchemaTable表 访问架构的方法。

    更多信息可以在这里找到。

    http://support.microsoft.com/kb/310107

    来自上述来源的示例

    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=DB";
    cn.Open();
    
    //Retrieve records from the Employees table into a DataReader.
    cmd.Connection = cn;
    cmd.CommandText = "SELECT Id, IntField, NullableIntField, VarcharField, DateField FROM SomeTable";
    
    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();
    
        2
  •  1
  •   marc_s    14 年前

    我认为你所做的可能是最好的方法。实际上,没有一个神奇的存储库能够保存所有这些信息。您可以从系统目录视图中找到有关存储过程参数的信息,但是结果集的形状、字段名和类型并没有存储在SQL Server系统视图中的任何位置,很遗憾。

        3
  •  1
  •   VladV    14 年前

    另一个选项(根据需要,可能比getSchemaTable()更好或更差)。
    以下代码为您提供了一个列结构与结果集相同的数据表:

    DataTable table = new DataTable();
    var cmd = new SqlCommand("...");
    using (var reader = cmd.Execute(CommandBehaviour.SchemaOnly))
        table.Load(reader);
    
        4
  •  0
  •   KM.    14 年前

    如果这是一次您需要做的事情,而不是每次调用过程时在运行时都要做的事情,那么只需修改结果集查询,以便使用 INTO ThrowArayTable :

    SELECT
        Col1, col2, col3, ...
        INTO ThrowArayTable     ----<<<add this line to existing result set query
        FROM ...
        WHERE ...
    

    运行应用程序或手动调用过程以生成throwaraytable。现在,您可以使用任何方法、ssms或information-schema.columns查找列aames和数据类型。

    只需记住将程序改回(删除 进入可传送的 值),因此它将实际返回结果集。