如何填充从存储过程的数据表存储过程、数据表

由网友(Angus(愛神))分享简介:可能重复: How我可以检索表中的存储过程,一个数据表 我想填充我的数据表。我创建了一个数据表tmpABCD,但我需要从一个存储过程中的值填充此。我不能进一步进行。的SqlConnection sqlcon =新的SqlConnection(ConfigurationManager.ConnectionStrings...

可能重复:   How我可以检索表中的存储过程,一个数据表

我想填充我的数据表。我创建了一个数据表tmpABCD,但我需要从一个存储过程中的值填充此。我不能进一步进行。

 的SqlConnection sqlcon =新的SqlConnection(ConfigurationManager.ConnectionStrings [DB]的ConnectionString。);
sqlcon.Open();
的SqlCommand CMD =新的SqlCommand(usp_GetABCD,sqlcon);

数据表DT =新的DataTable(tmpABCD);

dt.Columns.Add(新的DataColumn(A));
dt.Columns.Add(新的DataColumn(B));
dt.Columns.Add(新的DataColumn(C));
dt.Columns.Add(新的DataColumn(D));
 

解决方案

您不必手动添加列。只需使用 DataAdapter的,它是简单的:

 数据表表=新的DataTable();
使用(VAR CON =新的SqlConnection(ConfigurationManager.ConnectionStrings [DB。的ConnectionString))
使用(VAR CMD =新的SqlCommand(usp_GetABCD,CON))
使用(VAR DA =新的SqlDataAdapter(CMD))
{
   cmd.CommandType = CommandType.StoredProcedure;
   da.Fill(表);
}
 
数据库实验 第4关 修改多个数据表的存储过程

请注意,你甚至都不需要打开/关闭连接。这将隐含在 DataAdapter的

  

SELECT语句关联的连接对象必须是   有效的,但它并不需要开放。如果连接被关闭   填充被调用之前,它被打开以检索数据,然后关闭。如果   连接打开填充被调用之前,它仍然是开放的。

Possible Duplicate: How can i retrieve a table from stored procedure to a datatable

I am trying to populate my datatable. I have created a datatable tmpABCD but i need to populate this with the values from a stored procedure. I am not able to proceed further.

SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["DB"].ConnectionString);
sqlcon.Open();
SqlCommand cmd = new SqlCommand("usp_GetABCD", sqlcon);

DataTable dt = new DataTable("tmpABCD");

dt.Columns.Add(new DataColumn("A"));
dt.Columns.Add(new DataColumn("B"));
dt.Columns.Add(new DataColumn("C"));
dt.Columns.Add(new DataColumn("D"));

解决方案

You don't need to add the columns manually. Just use a DataAdapter and it's simple as:

DataTable table = new DataTable();
using(var con = new SqlConnection(ConfigurationManager.ConnectionStrings["DB"].ConnectionString))
using(var cmd = new SqlCommand("usp_GetABCD", con))
using(var da = new SqlDataAdapter(cmd))
{
   cmd.CommandType = CommandType.StoredProcedure;
   da.Fill(table);
}

Note that you even don't need to open/close the connection. That will be done implicitely by the DataAdapter.

The connection object associated with the SELECT statement must be valid, but it does not need to be open. If the connection is closed before Fill is called, it is opened to retrieve data, then closed. If the connection is open before Fill is called, it remains open.

阅读全文

相关推荐

最新文章