具有实际表名的数据集

use*_*007 6 c# stored-procedures dataset

我试图从我的存储过程中获取数据到我的数据集.问题是在数据集可视化工具中,实际的表名称即客户或员工不会只显示Table1,table2等.是否可以获取实际的表名?

   using (SqlConnection sqlConnection = new SqlConnection("Data Source=myserver;Initial Catalog=Northwind;Integrated Security=True"))
        {
            sqlConnection.Open();

            SqlDataAdapter da = new SqlDataAdapter("EXECUTE  [Northwind].[dbo].[GetCustomers_Employees] ", sqlConnection);
            DataSet ds = new DataSet();
            da.Fill(ds);
        }

CREATE PROCEDURE GetCustomers_Employees
AS
BEGIN
SELECT top 10 * from customers
select top 10 * from Employees
END
Run Code Online (Sandbox Code Playgroud)

数据集可视化器

Joe*_*Lee 6

您可以在执行填充操作时添加名称,如下所示:

da.Fill(ds, "MyTable");
Run Code Online (Sandbox Code Playgroud)

从那时起,您可以将表格称为

ds.Tables["MyTable"];
Run Code Online (Sandbox Code Playgroud)

而不是使用整数索引(即ds.Tables[0])

请看:http://msdn.microsoft.com/en-us/library/bh8kx08z(v = VS.100).aspx

编辑:

在您的情况下,您可以使用该TableName属性,如下所示:

da.Fill(ds);
ds.Tables[0].TableName = "Customers";
ds.Tables[1].TableName = "Employees";
Run Code Online (Sandbox Code Playgroud)

这是快速而肮脏的方法,但不是很一般.不幸的是,没有办法从SP获取表的名称,这可能是你想要的.一种方法是修改SP以返回输出参数:

CREATE PROCEDURE GetCustomers_Employees
   @tableNames varchar(20) OUTPUT
AS
BEGIN
    SET @tableNames = 'Customers,Employees'
    SELECT top 10 * from Customers
    SELECT top 10 * from Employees
END
Run Code Online (Sandbox Code Playgroud)

但是要使用它,您还必须修改您SqlDataAdapter的处理带有输出参数的存储过程:

using (SqlConnection = ...)
    {
       // sqlConnection.Open(); // Not really needed. Data Adapter will do this.

        SqlCommand cmd = new SqlCommand();
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandText = "GetCustomers_Employees";
        cmd.Connection = sqlConnection;

        // Create the parameter object and add it to the command
        SqlParameter param = new SqlParameter("@tableNames", SqlDbType.VarChar);
        param.Direction = ParameterDirection.Output;
        cmd.Parameters.Add(param);

        // Get the Data
        SqlDataAdapter da = new SqlDataAdapter();
        da.SelectCommand = cmd;
        DataSet ds = new DataSet(); 
        da.Fill(ds);

        // Set the names of the tables in the dataset
        string strTableNames = cmd.Parameters["@tableNames"].Value.ToString();
        string[] tableNames = strTableNames.split(',');

        for (int i=0; i<tableNames.Length; i++)
        {
            ds.Tables[i].TableName = tableNames[i];
        }
    }
Run Code Online (Sandbox Code Playgroud)

请注意,上面将处理返回的任意数量的表,因此您可以轻松地将其封装在一个函数中,您可能会发现它很有用:

DataSet function(string storedProcedureName, string connectionString)
{
    DataSet ds = new DataSet();
    ... // code above, without DataSet declaration
    return ds;
}
Run Code Online (Sandbox Code Playgroud)